package com.mzj.saas.mservice.lifePay.service;

import com.alibaba.fastjson.JSON;
import com.mzj.saas.commons.*;
import com.mzj.saas.commons.enums.*;
import com.mzj.saas.commons.util.ConvertUtils;
import com.mzj.saas.commons.util.DataUtils;
import com.mzj.saas.commons.vo.redis.TokenRedisVo;
import com.mzj.saas.config.pay.PayConfig;
import com.mzj.saas.mservice.backlog.entity.BacklogItem;
import com.mzj.saas.mservice.backlog.entity.BacklogItemContractBill;
import com.mzj.saas.mservice.backlog.entity.BacklogItemRecordSubmit;
import com.mzj.saas.mservice.backlog.repository.BacklogItemContractBillRepository;
import com.mzj.saas.mservice.backlog.repository.BacklogItemRecordSubmitRepository;
import com.mzj.saas.mservice.backlog.repository.BacklogItemRepository;
import com.mzj.saas.mservice.bill.entity.*;
import com.mzj.saas.mservice.bill.repository.*;
import com.mzj.saas.mservice.bill.vo.*;
import com.mzj.saas.mservice.community.entity.Community;
import com.mzj.saas.mservice.community.entity.CommunityBuild;
import com.mzj.saas.mservice.community.entity.CommunityBuildUnit;
import com.mzj.saas.mservice.community.repository.CommunityBuildRepository;
import com.mzj.saas.mservice.community.repository.CommunityBuildUnitRepository;
import com.mzj.saas.mservice.community.repository.CommunityRepository;
import com.mzj.saas.mservice.contract.entity.Contract;
import com.mzj.saas.mservice.contract.repository.ContractRepository;
import com.mzj.saas.mservice.eligible.entity.DepartmentHierarchy;
import com.mzj.saas.mservice.eligible.repository.DepartmentHierarchyRepository;
import com.mzj.saas.mservice.eligible.service.DepartmentHierarchyService;
import com.mzj.saas.mservice.house.entity.House;
import com.mzj.saas.mservice.house.entity.HouseMatchUser;
import com.mzj.saas.mservice.house.repository.HouseMatchUserRepository;
import com.mzj.saas.mservice.house.repository.HouseRepository;
import com.mzj.saas.mservice.lifePay.entity.*;
import com.mzj.saas.mservice.lifePay.repository.*;
import com.mzj.saas.mservice.lifePay.vo.*;
import com.mzj.saas.mservice.property.entity.EstateExpenseBill;
import com.mzj.saas.mservice.property.entity.EstatePaymentOrder;
import com.mzj.saas.mservice.property.entity.EstatePaymentOrderRelation;
import com.mzj.saas.mservice.property.entity.EstateRentBill;
import com.mzj.saas.mservice.property.repository.EstateExpenseBillRepository;
import com.mzj.saas.mservice.property.repository.EstatePaymentOrderRelationRepository;
import com.mzj.saas.mservice.property.repository.EstatePaymentOrderRepository;
import com.mzj.saas.mservice.property.repository.EstateRentBillRepository;
import com.mzj.saas.mservice.property.vo.EstateExpenseBillVO;
import com.mzj.saas.mservice.propertybill.entity.EstateExpenseBillDetail;
import com.mzj.saas.mservice.propertybill.repository.EstateExpenseBillDetailRepository;
import com.mzj.saas.mservice.propertybill.service.WithDrawService;
import com.mzj.saas.mservice.propertybill.vo.EstateExpenseBillDetailVO;
import com.mzj.saas.mservice.sys.entity.AppUser;
import com.mzj.saas.mservice.sys.entity.WechatAccount;
import com.mzj.saas.mservice.sys.repository.AppUserRepository;
import com.mzj.saas.mservice.sys.repository.WechatAccountRepository;
import com.mzj.saas.redis.RedisService;
import com.mzj.saas.sdk.pay.alipay.AliPayRequest;
import com.mzj.saas.sdk.pay.vo.AliPay;
import com.mzj.saas.sdk.pay.vo.WxPay;
import com.mzj.saas.sdk.pay.wxpay.WxPayRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SingleColumnRowMapper;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 生活缴费
 */
@Service
public class LifePayService {
    private static final Logger LOG = LoggerFactory.getLogger(LifePayService.class);

    @Autowired
    private RedisService redisService;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private HousePaymentBindRepository housePaymentBindRepository;
    @Autowired
    private LivingPaymentBindRepository livingPaymentBindRepository;
    @Autowired
    private LivingPaymentGroupRepository livingPaymentGroupRepository;
    @Autowired
    private LivingPaymentTotalRepository livingPaymentTotalRepository;
    @Autowired
    private CommunityRepository communityRepository;
    @Autowired
    private DepartmentHierarchyRepository departmentHierarchyRepository;
    @Autowired
    private HouseMatchUserRepository houseMatchUserRepository;
    @Autowired
    private AppUserRepository appUserRepository;
    @Autowired
    private RentBillRepository rentBillRepository;
    @Autowired
    private ExpenseBillRepository expenseBillRepository;
    @Autowired
    private EstateRentBillRepository estateRentBillRepository;
    @Autowired
    private EstateExpenseBillRepository estateExpenseBillRepository;
    @Autowired
    private HouseWaitPaymentDetailRepository houseWaitPaymentDetailRepository;
    @Autowired
    private HouseRepository houseRepository;
    @Autowired
    private PayConfig payConfig;
    @Autowired
    private WechatAccountRepository wechatAccountRepository;
    @Autowired
    private DepartmentHierarchyService departmentHierarchyService;
    @Autowired
    private LivingPaymentUserGroupRepository livingPaymentUserGroupRepository;
    @Autowired
    private HousePaymentOrderRelationRepository housePaymentOrderRelationRepository;
    @Autowired
    private RentBillRelationRepository rentBillRelationRepository;
    @Autowired
    private ContractRepository contractRepository;
    @Autowired
    private HousePaymentOrderRepository housePaymentOrderRepository;
    @Autowired
    private BacklogItemRepository backlogItemRepository;
    @Autowired
    private BacklogItemContractBillRepository backlogItemContractBillRepository;
    @Autowired
    private BacklogItemRecordSubmitRepository backlogItemRecordSubmitRepository;
    @Autowired
    private EstatePaymentOrderRepository estatePaymentOrderRepository;
    @Autowired
    private EstatePaymentOrderRelationRepository estatePaymentOrderRelationRepository;
    @Autowired
    private CommunityBuildRepository communityBuildRepository;
    @Autowired
    private CommunityBuildUnitRepository communityBuildUnitRepository;
    @Autowired
    private EstateExpenseBillDetailRepository estateExpenseBillDetailRepository;
    @Autowired
    private WithDrawService withDrawService;

    public ResultBean<Object> houseInformationSearch(String accessToken, RequestParameterVO vo) {
        LOG.info("LifePayService  houseInformationSearch, vo={}", JSON.toJSON(vo));

        // TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        List<Map<String, Object>> data = new ArrayList<>();
        Iterable<DepartmentHierarchy> DepartmentHierarchyList = departmentHierarchyRepository.findAll();

        if (vo == null) {
            return ResultBean.failedResultWithMsg("参数异常");
        }

        String houseSQL = "  SELECT  h.org_id orgId,h.owner_user_id ownerUserId,h.owner_name ownerName,h.house_nature houseNature,h.id houseId,h.residence_community_id communityId,h.building_num buildId,h.unit unitId,h.room_number roomNumber, "
                + "   h.address,c.name communityName,b.name buildName,u.name unitName,a1.name provinceName,a2.name cityName,a3.name districtName,a4.name streetName,a5.name bCommunityName  "
                + "   FROM saas_house h  " + "   LEFT JOIN saas_community c ON c.id=h.residence_community_id  "
                + "   LEFT JOIN saas_community_build b ON b.id=h.building_num  "
                + "   LEFT JOIN saas_community_build_unit u ON u.id=h.unit  "
                + "   LEFT JOIN sys_area a1 ON h.province_id=a1.id  " + "   LEFT JOIN sys_area a2 ON h.city_id=a2.id  "
                + "   LEFT JOIN sys_area a3 ON h.district_id=a3.id  "
                + "   LEFT JOIN sys_area a4 ON h.street_id=a4.id  "
                + "   LEFT JOIN sys_area a5 ON h.community_id=a5.id  ";

        StringBuilder housewhere = new StringBuilder();
        List<Object> args = new ArrayList<>();

        housewhere.append(" where 1 = 1  ");

        if (StringUtils.isNotBlank(vo.getCommunityId())) {
            housewhere.append(" and h.residence_community_id = ? ");
            args.add(vo.getCommunityId());

        }
        if (vo.getBuildId() != null) {
            housewhere.append("  and h.building_num = ?  ");
            args.add(vo.getBuildId());

        }
        if (vo.getUnitId() != null) {
            housewhere.append("  and h.unit = ?  ");
            args.add(vo.getUnitId());

        }
        if (StringUtils.isNotBlank(vo.getRoomNumber())) {
            housewhere.append(" and h.room_number = ? ");
            args.add(vo.getRoomNumber());

        }

        List<Map<String, Object>> houseData = jdbcTemplate.queryForList(houseSQL + housewhere, args.toArray());
        for (Map<String, Object> map : houseData) {
            Object orgId = map.get("orgId");
            if (orgId != null) {
                for (DepartmentHierarchy hierarchy : DepartmentHierarchyList) {
                    if (hierarchy.getOrgId().equals((Long) orgId)) {
                        map.put("orgName", hierarchy.getName());
                        break;
                    }
                }
            }

        }

        data.addAll(houseData);
        return ResultBean.successfulResult(data);
    }

    public ResultBean<Object> houseIdSearch(String accessToken, RequestParameterVO vo) {
        LOG.info("LifePayService  houseIdSearch   accessToken={} ", accessToken);

        // TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        List<Map<String, Object>> data = new ArrayList<>();
        Iterable<DepartmentHierarchy> DepartmentHierarchyList = departmentHierarchyRepository.findAll();

        if (vo == null) {
            return ResultBean.failedResultWithMsg("参数异常");
        }

        String houseSQL = "  SELECT  h.org_id orgId,h.owner_user_id ownerUserId,h.owner_name ownerName,h.house_nature houseNature,h.id houseId,h.residence_community_id communityId,h.building_num buildId,h.unit unitId,h.room_number roomNumber, "
                + "   h.address,c.name communityName,b.name buildName,u.name unitName,a1.name provinceName,a2.name cityName,a3.name districtName,a4.name streetName,a5.name bCommunityName  "
                + "   FROM saas_house h  " + "   LEFT JOIN saas_community c ON c.id=h.residence_community_id  "
                + "   LEFT JOIN saas_community_build b ON b.id=h.building_num  "
                + "   LEFT JOIN saas_community_build_unit u ON u.id=h.unit  "
                + "   LEFT JOIN sys_area a1 ON h.province_id=a1.id  " + "   LEFT JOIN sys_area a2 ON h.city_id=a2.id  "
                + "   LEFT JOIN sys_area a3 ON h.district_id=a3.id  "
                + "   LEFT JOIN sys_area a4 ON h.street_id=a4.id  "
                + "   LEFT JOIN sys_area a5 ON h.community_id=a5.id  ";

        StringBuilder where = new StringBuilder();
        List<Object> args = new ArrayList<>();

        where.append(" where 1 = 1  ");

        if (StringUtils.isNotBlank(vo.getHouseId())) {
            where.append(" and h.id = ? ");
            args.add(vo.getHouseId());
        }

        List<Map<String, Object>> houseData = jdbcTemplate.queryForList(houseSQL + where, args.toArray());

        for (Map<String, Object> map : houseData) {
            Object orgId = map.get("orgId");
            if (orgId != null) {
                for (DepartmentHierarchy hierarchy : DepartmentHierarchyList) {
                    if (hierarchy.getOrgId().equals((Long) orgId)) {
                        map.put("orgName", hierarchy.getName());
                        break;
                    }
                }
            }
        }

        data.addAll(houseData);
        return ResultBean.successfulResult(data);
    }

    public ResultBean<Object> houseBind(String accessToken, HousePaymentBindVO vo) {
        try {
            LOG.info("lifePayService  houseBind  accessToken={}, vo={}", accessToken, JSON.toJSONString(vo));

            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            String userId = tokenRedisVo.getId();

            if (StringUtils.isBlank(vo.getHouseId())) {
                return ResultBean.failedResultOfParamWithMsg("房屋id不能为空");
            }
            if (vo.getType() == null) {
                return ResultBean.failedResultOfParamWithMsg("房屋类型不能为空");
            }
            if (vo.getLivingPaymentGroupId() == null) {
                return ResultBean.failedResultOfParamWithMsg("分组id不能为空");
            }
            if (StringUtils.isBlank(vo.getHouseAddress())) {
                return ResultBean.failedResultOfParamWithMsg("房屋地址不能为空");
            }

            if (StringUtils.isBlank(vo.getPhone()) && StringUtils.isBlank(vo.getCode())) {
                //查询本人关联房屋
                List<String> houseIdList = getHouseIdList(userId);
                if (!houseIdList.contains(vo.getHouseId())) {
                    ResultBean<Object> resultBean = new ResultBean<>();
                    resultBean.setCode(StatusCode.ERROR_CODE_10001.getErrorCode());
                    if (vo.getType() == 1) {
                        resultBean.setMsg("请验证承租人手机号码");
                    } else {
                        resultBean.setMsg("请验证产权所有人手机号码");
                    }
                    resultBean.setResultData(1);
                    return resultBean;
                } else {
                    List<HousePaymentBind> bindList = housePaymentBindRepository.findByUserIdAndHouseIdAndStatus(userId, vo.getHouseId(), 1);
                    if (!bindList.isEmpty()) {
                        return ResultBean.failedResultWithMsg("房屋已绑定，无需重复绑定");
                    }

                    HousePaymentBind housePaymentBind = new HousePaymentBind();
                    BeanUtils.copyProperties(vo, housePaymentBind);
                    housePaymentBind.setStatus(1); // 绑定状态：1已绑定 2已解绑
                    housePaymentBind.setBindTime(new Date());
                    housePaymentBind.setUserId(userId);
                    housePaymentBindRepository.save(housePaymentBind);
                }
            }

            if (!StringUtils.isBlank(vo.getPhone()) && !StringUtils.isBlank(vo.getCode())) {
                // 验证验证码
                String redisPhone = redisService.getSmsCodeMobile(vo.getCode());
                if (!StringUtils.isBlank(redisPhone)) {
                    if (redisPhone.equals(vo.getPhone())) {
                        if (vo.getType() == 1) {
                            List<HouseMatchUser> matchUsers = houseMatchUserRepository.findHouseIdAndStatus(vo.getHouseId(), 1);
                            if (matchUsers.isEmpty()) {
                                return ResultBean.failedResultWithMsg("房屋没有承租人，不能绑定");
                            }
                            HouseMatchUser matchUser = matchUsers.get(0);
                            AppUser appUser = appUserRepository.findByIdOrEnterpriseUserId(matchUser.getMatchUserId(), matchUser.getMatchUserId());
                            if (!appUser.getPhone().equals(vo.getPhone())) {
                                return ResultBean.failedResultWithMsg("手机号码与承租人手机号码不符");
                            }
                        } else {
                            Optional<House> houseOptional = houseRepository.findById(vo.getHouseId());
                            House house = houseOptional.get();
                            if (!house.getOwnerMobile().equals(vo.getPhone())) {
                                return ResultBean.failedResultWithMsg("手机号码与产权所有人手机号码不符");
                            }
                        }

                        List<HousePaymentBind> bindList = housePaymentBindRepository.findByUserIdAndHouseIdAndStatus(userId, vo.getHouseId(), 1);
                        if (!bindList.isEmpty()) {
                            return ResultBean.failedResultWithMsg("房屋已绑定，无需重复绑定");
                        }

                        HousePaymentBind housePaymentBind = new HousePaymentBind();
                        BeanUtils.copyProperties(vo, housePaymentBind);
                        housePaymentBind.setStatus(1); // 绑定状态：1已绑定 2已解绑
                        housePaymentBind.setBindTime(new Date());
                        housePaymentBind.setUserId(userId);
                        housePaymentBindRepository.save(housePaymentBind);
                    } else {
                        return ResultBean.failedResultWithMsg("验证码不正确");
                    }
                } else {
                    return ResultBean.failedResultWithMsg("验证码未找到或已过期");
                }
            }

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 公租房承租人、公租房同住人、房产租客成员，房屋信息查询
     */
    public List<String> getHouseIdList(String userId) {
        String houseSql = "SELECT u.house_id AS houseId \n" +
                "FROM saas_house_match_user u \n" +
                "LEFT JOIN `saas_house` h ON u.house_id = h.`id`\n" +
                "WHERE u.match_user_id = ? AND u.status = 1 AND h.`lease_status` = 1\n" +
                "UNION \n" +
                "SELECT u.house_id AS houseId \n" +
                "FROM saas_house_match_user u\n" +
                "LEFT JOIN `saas_house` h ON u.house_id = h.`id` \n" +
                "LEFT JOIN (SELECT c.apply_id, us.id, us.enterprise_user_id FROM saas_house_eligible_apply_cohabit c LEFT JOIN saas_app_user us ON c.mobile = us.phone) c1 \n" +
                "ON u.apply_id = c1.apply_id \n" +
                "WHERE (c1.id = ? OR c1.enterprise_user_id = ?) AND u.status = 1 AND h.`lease_status` = 1\n" +
                "UNION \n" +
                "SELECT u2.community_house_id AS houseId \n" +
                "FROM saas_community_house_user u2\n" +
                "LEFT JOIN `saas_house` h ON u2.community_house_id = h.`id` \n" +
                "LEFT JOIN saas_app_user us ON us.phone = u2.mobile\n" +
                "WHERE (us.id = ? OR us.enterprise_user_id = ?) AND u2.status = 1";
        return jdbcTemplate.query(houseSql, new SingleColumnRowMapper<>(String.class), userId, userId, userId, userId, userId);
    }

    public ResultBean<Object> livingBind(String accessToken, LivingPaymentBindVO vo) {
        LOG.info("LifePayService livingBind, vo={}", JSON.toJSONString(vo));
        if (vo == null) {
            return ResultBean.failedResultOfParamWithMsg("参数异常");
        }

        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        LivingPaymentBind livingPaymentBind = new LivingPaymentBind();

        if (StringUtils.isNotEmpty(vo.getBillNumber())) {
            LivingPaymentBind entity = livingPaymentBindRepository.findByBillNumber(vo.getBillNumber());
            if (entity != null) {
                return ResultBean.failedResultOfParamWithMsg("账单已存在，无需重复");
            }
        }

        BeanUtils.copyProperties(vo, livingPaymentBind);
        livingPaymentBind.setStatus(1);// 数据状态：1正常 2已删除
        livingPaymentBind.setCreateTime(new Date());
        livingPaymentBind.setUserId(tokenRedisVo.getId());

        livingPaymentBindRepository.save(livingPaymentBind);
        return ResultBean.successfulResult(null);
    }

    /*public ResultBean<Object> payManagementPage(String accessToken, Integer pageNumber, Integer pageSize) {
        LOG.info("lifePayService  payManagementPage   accessToken ={}", accessToken);
        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);

        // 先查询是否有房屋绑定信息，如果有:
        List<HousePaymentBind> housePaymentBindList = housePaymentBindRepository.findByUserId(tokenRedisVo.getId());
        if (housePaymentBindList.size() > 0) {
            for (HousePaymentBind hpBind : housePaymentBindList) {
                StringBuilder chargeTypeName = new StringBuilder();
                String chargeTypeNameStr = null; // 费用类型合成的名称
                // 查看绑定数据中，缴费名称是否为空，如果为空继续下面查询
                if (StringUtils.isBlank(hpBind.getName())) {
                    // 查询房屋租金与押金账单、其它费用账单,即待缴费费用账单 [type 房屋类型：1公租房 2物业房产]
                    // 获取到所有账单数据后，构建列表展示数据，所有费用按类型名称合并成一个名字(房屋费用显示该房屋下所有费用类型)
                    if (hpBind.getType().intValue() == 1) {
                        List<RentBill> rentBillList = rentBillRepository
                                .findByHouseIdAndPaymentStatus(hpBind.getHouseId(), 0);
                        List<ExpenseBill> expenseBillList = expenseBillRepository
                                .findByHouseIdAndPaymentStatus(hpBind.getHouseId(), 0);

                        Map<Integer, List<RentBill>> rentBillMap = rentBillList.stream()
                                .collect(Collectors.groupingBy(RentBill::getChargeType));

                        Map<Integer, List<ExpenseBill>> expenseBillMap = expenseBillList.stream()
                                .collect(Collectors.groupingBy(ExpenseBill::getChargeType));
                        // 1租金 2押金
                        for (Integer chargeType : rentBillMap.keySet()) {
                            switch (chargeType) {
                                case 1:
                                    chargeTypeName.append("租金").append(",");
                                    break;
                                case 2:
                                    chargeTypeName.append("押金").append(",");
                                    break;
                            }
                        }
                        // 1水费 2电费 3物业费 4宽带费 5电视费 6煤气费 7暖气费
                        for (Integer chargeType : expenseBillMap.keySet()) {
                            switch (chargeType) {
                                case 1:
                                    chargeTypeName.append("水费").append(",");
                                    break;
                                case 2:
                                    chargeTypeName.append("电费").append(",");
                                    break;
                                case 3:
                                    chargeTypeName.append("物业费").append(",");
                                    break;
                                case 4:
                                    chargeTypeName.append("宽带费").append(",");
                                    break;
                                case 5:
                                    chargeTypeName.append("电视费").append(",");
                                    break;
                                case 6:
                                    chargeTypeName.append("煤气费").append(",");
                                    break;
                                case 7:
                                    chargeTypeName.append("暖气费").append(",");
                                    break;
                            }
                        }

                    } else {
                        // 物业房产
                        List<EstateRentBill> estateRentBillList = estateRentBillRepository
                                .findByHouseIdAndPaymentStatus(hpBind.getHouseId(), 0);
                        List<EstateExpenseBill> estateExpenseBillList = estateExpenseBillRepository
                                .findByHouseIdAndPaymentStatus(hpBind.getHouseId(), 0);

                        Map<Integer, List<EstateRentBill>> estateRentBillMap = estateRentBillList.stream()
                                .collect(Collectors.groupingBy(EstateRentBill::getChargeType));
                        Map<Integer, List<EstateExpenseBill>> estateExpenseBillMap = estateExpenseBillList.stream()
                                .collect(Collectors.groupingBy(EstateExpenseBill::getChargeType));
                        for (Integer chargeType : estateRentBillMap.keySet()) {
                            switch (chargeType) {
                                case 1:
                                    chargeTypeName.append("租金").append(",");
                                    break;
                                case 2:
                                    chargeTypeName.append("押金").append(",");
                                    break;
                            }
                        }

                        for (Integer chargeType : estateExpenseBillMap.keySet()) {
                            switch (chargeType) {
                                case 1:
                                    chargeTypeName.append("水费").append(",");
                                    break;
                                case 2:
                                    chargeTypeName.append("电费").append(",");
                                    break;
                                case 3:
                                    chargeTypeName.append("物业费").append(",");
                                    break;
                                case 4:
                                    chargeTypeName.append("宽带费").append(",");
                                    break;
                                case 5:
                                    chargeTypeName.append("电视费").append(",");
                                    break;
                                case 6:
                                    chargeTypeName.append("煤气费").append(",");
                                    break;
                                case 7:
                                    chargeTypeName.append("暖气费").append(",");
                                    break;
                            }
                        }
                    }
                }

                if (chargeTypeName.toString().length() > 0) {
                    chargeTypeNameStr = chargeTypeName.toString().substring(0,
                            chargeTypeName.toString().lastIndexOf(","));
                }
                if (StringUtils.isBlank(hpBind.getName())) {
                    hpBind.setName(chargeTypeNameStr);
                }
            }
        }

        String sql = " select null houseId,id,user_id userId,type,name,account,living_payment_group_id livingPaymentGroupId,address from  saas_living_payment_bind where status=1 and pay_status=0 and user_id = "
                + "'" + tokenRedisVo.getId() + "'";

        List<Map<String, Object>> data = jdbcTemplate.queryForList(sql);
        Iterable<User> userList = userRepository.findAll();
        List<LivingPaymentGroup> livingPaymentGroupList = livingPaymentGroupRepository.findAll();

        for (HousePaymentBind h : housePaymentBindList) {
            Map<String, Object> map = new HashMap<>();

            map.put("id", h.getId());
            map.put("userId", h.getUserId());
            map.put("name", h.getName());
            map.put("livingPaymentGroupId", h.getLivingPaymentGroupId());
            map.put("address", h.getHouseAddress());
            map.put("houseId", h.getHouseId());

            data.add(map);
        }

        for (Map<String, Object> map : data) {

            String userId = (String) map.get("userId");
            for (User user : userList) {
                if (user.getId().equals(userId)) {
                    map.put("userName", user.getName());
                }
            }

            Long livingPaymentGroupId = (Long) map.get("livingPaymentGroupId");
            for (LivingPaymentGroup pg : livingPaymentGroupList) {
                if (pg.getId().equals(livingPaymentGroupId)) {
                    map.put("livingPaymentGroupName", pg.getName());
                }
            }
        }
        return ResultBean.successfulResult(data);
    }*/

    public ResultBean<Object> payManagementPage(String accessToken) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);

            List<HousePaymentBind> housePaymentBindList = housePaymentBindRepository.findByUserId(tokenRedisVo.getId());
            if (housePaymentBindList.size() > 0) {
                for (HousePaymentBind hpBind : housePaymentBindList) {
                    StringBuilder chargeTypeName = new StringBuilder();
                    String chargeTypeNameStr = null; // 费用类型合成的名称

                    // 查看绑定数据中，缴费名称是否为空，如果为空继续下面查询
                    if (StringUtils.isBlank(hpBind.getName())) {
                        // 查询房屋租金与押金账单、其它费用账单，即待缴费费用账单 [type 房屋类型：1公租房 2物业房产]
                        // 获取到所有账单数据后，构建列表展示数据，所有费用按类型名称合并成一个名字(房屋费用显示该房屋下所有费用类型)
                        if (hpBind.getType().intValue() == 1) {
                            List<RentBill> rentBillList = rentBillRepository
                                    .findByHouseIdAndPaymentStatusAndAuditStatus(hpBind.getHouseId(), 0, 1);
                            List<ExpenseBill> expenseBillList = expenseBillRepository
                                    .findByHouseIdAndPaymentStatusAndAuditStatus(hpBind.getHouseId(), 0, 1);

                            Map<Integer, List<RentBill>> rentBillMap = rentBillList.stream()
                                    .collect(Collectors.groupingBy(RentBill::getChargeType));

                            Map<Integer, List<ExpenseBill>> expenseBillMap = expenseBillList.stream()
                                    .collect(Collectors.groupingBy(ExpenseBill::getChargeType));
                            // 1租金 2押金
                            for (Integer chargeType : rentBillMap.keySet()) {
                                switch (chargeType) {
                                    case 1:
                                        chargeTypeName.append("租金").append(",");
                                        break;
                                    case 2:
                                        chargeTypeName.append("押金").append(",");
                                        break;
                                }
                            }
                            // 1水费 2电费 3物业费 4宽带费 5电视费 6煤气费 7暖气费
                            for (Integer chargeType : expenseBillMap.keySet()) {
                                switch (chargeType) {
                                    case 1:
                                        chargeTypeName.append("水费").append(",");
                                        break;
                                    case 2:
                                        chargeTypeName.append("电费").append(",");
                                        break;
                                    case 3:
                                        chargeTypeName.append("物业费").append(",");
                                        break;
                                    case 4:
                                        chargeTypeName.append("宽带费").append(",");
                                        break;
                                    case 5:
                                        chargeTypeName.append("电视费").append(",");
                                        break;
                                    case 6:
                                        chargeTypeName.append("燃气费").append(",");
                                        break;
                                    case 7:
                                        chargeTypeName.append("暖气费").append(",");
                                        break;
                                }
                            }
                        } else {
                            // 物业房产
                            List<EstateRentBill> estateRentBillList = estateRentBillRepository
                                    .findByHouseIdAndPaymentStatusAndAuditStatus(hpBind.getHouseId(), 0, 1);
                            List<EstateExpenseBill> estateExpenseBillList = estateExpenseBillRepository
                                    .findByHouseIdAndPaymentStatusAndAuditStatus(hpBind.getHouseId(), 0, 1);

                            Map<Integer, List<EstateRentBill>> estateRentBillMap = estateRentBillList.stream()
                                    .collect(Collectors.groupingBy(EstateRentBill::getChargeType));
                            Map<Integer, List<EstateExpenseBill>> estateExpenseBillMap = estateExpenseBillList.stream()
                                    .collect(Collectors.groupingBy(EstateExpenseBill::getChargeType));
                            for (Integer chargeType : estateRentBillMap.keySet()) {
                                switch (chargeType) {
                                    case 1:
                                        chargeTypeName.append("租金").append(",");
                                        break;
                                    case 2:
                                        chargeTypeName.append("押金").append(",");
                                        break;
                                }
                            }

                            for (Integer chargeType : estateExpenseBillMap.keySet()) {
                                switch (chargeType) {
                                    case 1:
                                        chargeTypeName.append("水费").append(",");
                                        break;
                                    case 2:
                                        chargeTypeName.append("电费").append(",");
                                        break;
                                    case 3:
                                        chargeTypeName.append("物业费").append(",");
                                        break;
                                    case 4:
                                        chargeTypeName.append("宽带费").append(",");
                                        break;
                                    case 5:
                                        chargeTypeName.append("电视费").append(",");
                                        break;
                                    case 6:
                                        chargeTypeName.append("燃气费").append(",");
                                        break;
                                    case 7:
                                        chargeTypeName.append("暖气费").append(",");
                                        break;
                                }
                            }
                        }
                    }

                    if (chargeTypeName.toString().length() > 0) {
                        chargeTypeNameStr = chargeTypeName.toString().substring(0, chargeTypeName.toString().lastIndexOf(","));
                    }
                    if (StringUtils.isBlank(hpBind.getName())) {
                        hpBind.setName(chargeTypeNameStr);
                    }
                }
            }

            String sql = "select null houseId,id,user_id userId,type,name,account,living_payment_group_id livingPaymentGroupId,address " +
                    "from saas_living_payment_bind where status = 1 and pay_status = 0 and user_id = ?";
            List<Map<String, Object>> data = jdbcTemplate.queryForList(sql, tokenRedisVo.getId());
            for (HousePaymentBind h : housePaymentBindList) {
                Map<String, Object> map = new HashMap<>();
                map.put("id", h.getId());
                map.put("userId", h.getUserId());
                map.put("name", h.getName());
                map.put("livingPaymentGroupId", h.getLivingPaymentGroupId());
                map.put("address", h.getHouseAddress());
                map.put("houseId", h.getHouseId());
                data.add(map);
            }

            //查询用户名称
            List<String> userIds = data.stream().filter(vo -> vo.get("userId") != null).map(vo -> vo.get("userId").toString()).distinct().collect(Collectors.toList());
            if (!userIds.isEmpty()) {
                List<AppUser> appUsers = appUserRepository.findByIdOrEnterpriseIn(userIds, userIds);
                for (Map map : data) {
                    for (AppUser appUser : appUsers) {
                        if (map.get("userId").equals(appUser.getId()) || map.get("userId").equals(appUser.getEnterpriseUserId())) {
                            map.put("userName", appUser.getName());
                        }
                    }
                }
            }

            //查询分组名称
            List<Long> groupIds = data.stream().filter(vo -> vo.get("livingPaymentGroupId") != null).map(vo -> Long.parseLong(vo.get("livingPaymentGroupId").toString())).distinct().collect(Collectors.toList());
            if (!groupIds.isEmpty()) {
                Map<Long, String> map = livingPaymentUserGroupRepository.findByIdIn(groupIds).stream().collect(Collectors.toMap(LivingPaymentUserGroup::getId, LivingPaymentUserGroup::getName));
                if (!map.isEmpty()) {
                    data.forEach(vo -> vo.put("livingPaymentGroupName", map.get(Long.parseLong(vo.get("livingPaymentGroupId").toString()))));
                }
            }

            return ResultBean.successfulResult(data);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> findGroup(String accessToken) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();

            List<LivingPaymentUserGroup> userGroups = livingPaymentUserGroupRepository.findByUserId(userId);
            //同步默认分组
            if (userGroups.isEmpty()) {
                List<LivingPaymentGroup> groups = livingPaymentGroupRepository.findAll();
                for (LivingPaymentGroup group : groups) {
                    LivingPaymentUserGroup userGroup = new LivingPaymentUserGroup();
                    userGroup.setName(group.getName());
                    userGroup.setUserId(userId);
                    userGroup.setType(1);
                    userGroups.add(userGroup);
                }
                livingPaymentUserGroupRepository.saveAll(userGroups);
            }

            return ResultBean.successfulResult(userGroups);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> addGroup(String accessToken, LivingPaymentGroupVO vo) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();

            if (StringUtils.isBlank(vo.getName())) {
                return ResultBean.failedResultOfParamWithMsg("分组名称为空");
            }

            LivingPaymentUserGroup entity = livingPaymentUserGroupRepository.findByUserIdAndName(userId, vo.getName());
            if (entity != null) {
                return ResultBean.failedResultOfParamWithMsg("分组名称已存在");
            }

            LivingPaymentUserGroup userGroup = new LivingPaymentUserGroup();
            userGroup.setName(vo.getName());
            userGroup.setUserId(userId);
            userGroup.setType(2);
            livingPaymentUserGroupRepository.save(userGroup);

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> updateGroup(String accessToken, LivingPaymentGroupVO vo) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();

            if (vo.getId() == null) {
                return ResultBean.failedResultOfParamWithMsg("分组id为空");
            }
            if (StringUtils.isBlank(vo.getName())) {
                return ResultBean.failedResultOfParamWithMsg("分组名称为空");
            }

            Optional<LivingPaymentUserGroup> optional = livingPaymentUserGroupRepository.findById(vo.getId());
            if (!optional.isPresent()) {
                return ResultBean.failedResultWithMsg("分组不存在");
            }
            LivingPaymentUserGroup userGroup = optional.get();

            if (!vo.getName().equals(userGroup.getName())) {
                LivingPaymentUserGroup entity = livingPaymentUserGroupRepository.findByUserIdAndName(userId, vo.getName());
                if (entity != null) {
                    return ResultBean.failedResultOfParamWithMsg("分组名称已存在");
                }
            }

            userGroup.setName(vo.getName());
            livingPaymentUserGroupRepository.save(userGroup);

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> deleteGroup(String accessToken, Long id) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }

            Optional<LivingPaymentUserGroup> optional = livingPaymentUserGroupRepository.findById(id);
            if (!optional.isPresent()) {
                return ResultBean.failedResultWithMsg("分组不存在");
            }

            livingPaymentUserGroupRepository.deleteById(id);
            // 删除分组下相关数据
            housePaymentBindRepository.deleteByLivingPaymentGroupId(id);
            livingPaymentBindRepository.deleteByLivingPaymentGroupId(id);

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> updatePay(String accessToken, PaymentBindRequest vo) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }

            if (vo == null) {
                return ResultBean.failedResultWithMsg("参数异常");
            }
            if (vo.getId() == null) {
                return ResultBean.failedResultWithMsg("id不能为空");
            }
            if (vo.getBindType() == null) {
                return ResultBean.failedResultWithMsg("绑定类型不能为空");
            }

            if (vo.getBindType() == 1) {
                Optional<HousePaymentBind> housePaymentBindOptional = housePaymentBindRepository.findById(vo.getId());
                if (!housePaymentBindOptional.isPresent()) {
                    return ResultBean.failedResultWithMsg("数据不存在");
                }
                HousePaymentBind housePaymentBind = housePaymentBindOptional.get();
                housePaymentBind.setName(vo.getName());
                housePaymentBindRepository.save(housePaymentBind);
            }

            if (vo.getBindType() == 2) {
                Optional<LivingPaymentBind> livingPaymentBindOptional = livingPaymentBindRepository.findById(vo.getId());
                if (!livingPaymentBindOptional.isPresent()) {
                    return ResultBean.failedResultWithMsg("数据不存在");
                }
                LivingPaymentBind livingPaymentBind = livingPaymentBindOptional.get();
                livingPaymentBind.setName(vo.getName());
                livingPaymentBindRepository.save(livingPaymentBind);
            }

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> deletePay(String accessToken, PaymentBindRequest vo) {
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }

            if (vo.getBindType() == null) {
                return ResultBean.failedResultWithMsg("绑定类型不能为空");
            }

            if (vo.getBindType() == 1) {
                Optional<HousePaymentBind> housePaymentBindOptional = housePaymentBindRepository.findById(vo.getId());
                if (!housePaymentBindOptional.isPresent()) {
                    return ResultBean.failedResultWithMsg("数据不存在");
                }
                housePaymentBindRepository.deleteById(vo.getId());
            }

            if (vo.getBindType() == 2) {
                Optional<LivingPaymentBind> livingPaymentBindOptional = livingPaymentBindRepository.findById(vo.getId());
                if (!livingPaymentBindOptional.isPresent()) {
                    return ResultBean.failedResultWithMsg("数据不存在");
                }
                LivingPaymentBind livingPaymentBind = livingPaymentBindOptional.get();
                livingPaymentBind.setStatus(vo.getStatus());
                livingPaymentBindRepository.save(livingPaymentBind);
            }

            return ResultBean.successfulResult(null);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /**
     * 缴费记录-月份全类型统计
     * @param accessToken
     * @param statDate
     * @return
     */
    public ResultBean<Object> recordDetails(String accessToken, String statDate) {
        LOG.info("lifePayService recordDetails, accessToken={}, statDate={}", accessToken, statDate);
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }

            List<LivingPaymentTotal> totalList = livingPaymentTotalRepository.findByStatDateAndUserId(statDate, tokenRedisVo.getId());

            List<LivingPaymentTotalVO> voList = new ArrayList<>();
            for (LivingPaymentTotal total : totalList) {
                LivingPaymentTotalVO vo = new LivingPaymentTotalVO();
                vo.setId(total.getId());
                vo.setUserId(total.getUserId());
                vo.setStatDate(total.getStatDate());
                vo.setType(total.getType());
                vo.setTotalAmount(ConvertUtils.fen2yuan(total.getTotalAmount()));
                voList.add(vo);
            }

            return ResultBean.successfulResult(voList);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> recordDetailsByType(String accessToken, String statDate, Integer type) {
        LOG.info("lifePayService recordDetailsByType, accessToken={}, statDate={}, type={}", accessToken, statDate, type);
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            String SQL = "select t.* from saas_living_payment_total t";
            StringBuilder where = new StringBuilder(" WHERE 1 = 1 and t.type = ? and t.user_id= ?");

            List<Object> args = new ArrayList<>();
            args.add(type);
            args.add(tokenRedisVo.getId());

            if (StringUtils.isNotBlank(statDate)) {
                where.append(" and LEFT(t.stat_date,4) = ?");
                args.add(statDate);
            }

            // 查询数据
            where.append(" ORDER BY t.stat_date asc");
            List<LivingPaymentTotalVO> data = jdbcTemplate.query(SQL + where, new BeanPropertyRowMapper<>(LivingPaymentTotalVO.class),
                    args.toArray());
            for (LivingPaymentTotalVO vo : data) {
                vo.setTotalAmount(ConvertUtils.fen2yuan(vo.getTotalAmount().intValue()));
            }

            return ResultBean.successfulResult(data);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> paymentDetails(String accessToken, String statDate, Integer type) {
        LOG.info("lifePayService paymentDetails, accessToken={}, statDate={}, type={}", accessToken, statDate, type);
        try {
            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();

            Integer businessType = null;
            if (type == 1) {
                businessType = 8;
            } else if (type == 2) {
                businessType = 1;
            } else if (type == 3) {
                businessType = 2;
            } else if (type == 4) {
                businessType = 3;
            } else if (type == 5) {
                businessType = 4;
            } else if (type == 6) {
                businessType = 5;
            } else if (type == 7) {
                businessType = 6;
            } else if (type == 8) {
                businessType = 7;
            } else if (type == 9) {
                businessType = 9;
            }

            String sql = "SELECT *,2 AS billType FROM  \n" +
                    "(SELECT r.id,r.business_type AS TYPE,r.bill_amount AS amount,o.pay_user_id AS userId,o.pay_time AS paymentTime,o.pay_result,\n" +
                    "b1.house_id AS houseId1,b2.house_id AS houseId2,\n" +
                    "b1.community_id AS communityId1,b2.community_id AS communityId2,b1.building_num AS buildingNum1,b2.building_num AS buildingNum2,\n" +
                    "b1.unit AS unit1,b2.unit AS unit2,b1.room_number AS roomNumber1,b2.room_number AS roomNumber2\n" +
                    "FROM saas_house_payment_order_relation r JOIN saas_house_payment_order o\n" +
                    "ON r.order_number = o.order_number\n" +
                    "LEFT JOIN saas_rent_bill b1 ON r.bill_id = b1.id\n" +
                    "LEFT JOIN saas_expense_bill b2 ON r.bill_id = b2.id\n" +
                    "UNION ALL\n" +
                    "SELECT r.id,r.business_type AS TYPE,r.bill_amount AS amnount,o.pay_user_id AS userId,o.pay_time AS paymentTime,o.pay_result,\n" +
                    "b1.house_id AS houseId1,b2.house_id AS houseId2,\n" +
                    "b1.community_id AS communityId1,b2.community_id AS communityId2,b1.building_num AS buildingNum1,b2.building_num AS buildingNum2,\n" +
                    "b1.unit AS unit1,b2.unit AS unit2,b1.room_number AS roomNumber1,b2.room_number AS roomNumber2\n" +
                    "FROM saas_estate_payment_order_relation r JOIN saas_estate_payment_order o\n" +
                    "ON r.order_number = o.order_number\n" +
                    "LEFT JOIN saas_estate_rent_bill b1 ON r.bill_id = b1.id\n" +
                    "LEFT JOIN saas_estate_expense_bill b2 ON r.bill_id = b2.id) t";
            StringBuilder where = new StringBuilder();
            where.append(" where t.userId = ? AND DATE_FORMAT(t.paymentTime,'%Y') = ? and t.type = ? AND t.pay_result = 1");
            List<Object> args = new ArrayList<>();
            args.add(userId);
            args.add(statDate);
            args.add(businessType);
            where.append(" ORDER BY t.paymentTime asc");

            List<PaymentDetailsVO> data = jdbcTemplate.query(sql + where, new BeanPropertyRowMapper<>(PaymentDetailsVO.class), args.toArray());
            for (PaymentDetailsVO vo : data) {
                vo.setType(type);
                vo.setAmount(ConvertUtils.fen2yuan(vo.getAmount().intValue()));
                vo.setPaymentTime(DateUtils.format(vo.getPaymentTime(), DateUtils.FORMAT_DATETIME_14, DateUtils.FORMAT_DATETIME_14));

                if (type == 8 || type == 9) {
                    vo.setHouseId(vo.getHouseId1());
                    vo.setAccount(vo.getHouseId1());
                    vo.setCommunityId(vo.getCommunityId1());
                    vo.setBuildingNum(vo.getBuildingNum1());
                    vo.setUnit(vo.getUnit1());
                    vo.setRoomNumber(vo.getRoomNumber1());
                } else {
                    vo.setHouseId(vo.getHouseId2());
                    vo.setAccount(vo.getHouseId2());
                    vo.setCommunityId(vo.getCommunityId2());
                    vo.setBuildingNum(vo.getBuildingNum2());
                    vo.setUnit(vo.getUnit2());
                    vo.setRoomNumber(vo.getRoomNumber2());
                }
            }

            // 查询小区名称
            List<String> residenceCommunityIds = data.stream().filter(vo -> vo.getCommunityId() != null)
                    .map(PaymentDetailsVO::getCommunityId).distinct().collect(Collectors.toList());
            if (!residenceCommunityIds.isEmpty()) {
                Map<String, String> map = communityRepository.findByIdIn(residenceCommunityIds).stream()
                        .collect(Collectors.toMap(Community::getId, Community::getName));
                if (!map.isEmpty()) {
                    data.forEach(vo -> vo.setCommunityName(map.get(vo.getCommunityId())));
                }
            }
            // 查询楼栋名称
            List<Long> buildingIds = data.stream().filter(vo -> vo.getBuildingNum() != null)
                    .map(PaymentDetailsVO::getBuildingNum).distinct().collect(Collectors.toList());
            if (!buildingIds.isEmpty()) {
                Map<Long, String> map = communityBuildRepository.findByIdIn(buildingIds).stream()
                        .collect(Collectors.toMap(CommunityBuild::getId, CommunityBuild::getName));
                if (!map.isEmpty()) {
                    data.forEach(vo -> vo.setBuildingName(map.get(vo.getBuildingNum())));
                }
            }
            // 查询单元名称
            List<Long> unitIds = data.stream().filter(vo -> vo.getUnit() != null).map(PaymentDetailsVO::getUnit)
                    .distinct().collect(Collectors.toList());
            if (!unitIds.isEmpty()) {
                Map<Long, String> map = communityBuildUnitRepository.findByIdIn(unitIds).stream()
                        .collect(Collectors.toMap(CommunityBuildUnit::getId, CommunityBuildUnit::getName));
                if (!map.isEmpty()) {
                    data.forEach(vo -> vo.setUnitName(map.get(vo.getUnit())));
                }
            }

            //房屋信息
            for (PaymentDetailsVO vo : data) {
                vo.setAddress(vo.getCommunityName() + vo.getBuildingName() + "栋" + vo.getUnitName() + "单元" + vo.getRoomNumber() + "号");
            }

            return ResultBean.successfulResult(data);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> myPayPage(String accessToken) {
        LOG.info("lifePayService   myPayPage    accessToken ={}", accessToken);

        TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
        String userId = tokenRedisVo.getId();

        List<HousePaymentBind> list1 = housePaymentBindRepository.findByUserId(userId);
        List<LivingPaymentBind> list2 = livingPaymentBindRepository.findByUserIdAndPayStatusAndStatus(tokenRedisVo.getId(), 0, 1);

        Map<String, Object> map = new HashMap<>();
        map.put("housePaymentBind", list1);
        map.put("livingPaymentBind", list2);

        return ResultBean.successfulResult(map);
    }

    /*public ResultBean<Object> relatedHousesPayPage(String accessToken, String houseId, Integer type) {
        try {
            if (StringUtils.isBlank(houseId)) {
                return ResultBean.failedResultWithMsg("房屋id不能为空");
            }
            if (type == null) {
                return ResultBean.failedResultWithMsg("房屋类型不能为空");
            }

            Map<String, Object> map = new HashMap<>();
            List<ExpenseBillVO> expenseBillVOList = new ArrayList<>();
            List<RentBillVO> rentBillVOList = new ArrayList<>();

            List<EstateExpenseBillVO> estateExpenseBillVOList = new ArrayList<>();
            List<RentBillVO> estateRentBillVOList = new ArrayList<>();

            // 手续费比例
            String platStr = redisService.getValue("platform.commission");
            BigDecimal commission = DataUtils.IntegerToBigdecimal(Integer.valueOf(platStr));

            // 房屋类型：1公租房 2物业房产
            if (type.equals(1)) {
                //其他费用
                List<ExpenseBill> expenseBillList = expenseBillRepository.findByHouseIdAndPaymentStatusAndAuditStatus(houseId, 0, 1);
                expenseBillList.forEach(e -> {
                    ExpenseBillVO expenseBillVO = new ExpenseBillVO();
                    BeanUtils.copyProperties(e, expenseBillVO);
                    expenseBillVO.setStartTime(DateUtils.format(e.getStartTime(), DateUtils.FORMAT_DATE_8));
                    expenseBillVO.setEndTime(DateUtils.format(e.getEndTime(), DateUtils.FORMAT_DATE_8));
                    expenseBillVO.setShouldPayTime(e.getShouldPayTime() == null ? null : DateUtils.format(e.getShouldPayTime(), DateUtils.FORMAT_DATE_8));
                    expenseBillVO.setCost(ConvertUtils.fen2yuan(e.getCost()));
                    expenseBillVOList.add(expenseBillVO);
                });

                for (ExpenseBillVO expenseBillVO : expenseBillVOList) {
                    List<HouseWaitPaymentDetail> houseWaitPaymentDetailList = houseWaitPaymentDetailRepository.findByExpenseBillId(expenseBillVO.getId());
                    if (houseWaitPaymentDetailList.size() > 0) {
                        HouseWaitPaymentDetail detail = houseWaitPaymentDetailList.get(0);
                        HouseWaitPaymentDetailVO detailVO = new HouseWaitPaymentDetailVO();
                        BeanUtils.copyProperties(detail, detailVO);
                        if (detail.getWaterUnitPrice() != null) {
                            detailVO.setWaterUnitPrice(ConvertUtils.fen2yuan(detail.getWaterUnitPrice()));
                        }
                        if (detail.getElectricUnitPrice() != null) {
                            detailVO.setElectricUnitPrice(ConvertUtils.fen2yuan(detail.getElectricUnitPrice()));
                        }
                        if (detail.getGasUnitPrice() != null) {
                            detailVO.setGasUnitPrice(ConvertUtils.fen2yuan(detail.getGasUnitPrice()));
                        }
                        if (detail.getHeatingBill() != null) {
                            detailVO.setHeatingBill(ConvertUtils.fen2yuan(detail.getHeatingBill()));
                        }
                        if (detail.getPropertyFee() != null) {
                            detailVO.setPropertyFee(ConvertUtils.fen2yuan(detail.getPropertyFee()));
                        }
                        if (detail.getTvFee() != null) {
                            detailVO.setTvFee(ConvertUtils.fen2yuan(detail.getTvFee()));
                        }
                        if (detail.getBroadBandCharges() != null) {
                            detailVO.setBroadBandCharges(ConvertUtils.fen2yuan(detail.getBroadBandCharges()));
                        }
                        expenseBillVO.setHouseWaitPaymentDetail(detailVO);
                    }
                }

                // 公租房-租金/押金账单明细
                List<RentBill> rentBillList = rentBillRepository.findByHouseIdAndPaymentStatusAndAuditStatus(houseId, 0, 1);
                rentBillList.forEach(r -> {
                    RentBillVO rentBillVO = new RentBillVO();
                    BeanUtils.copyProperties(r, rentBillVO);
                    rentBillVO.setStartTime(DateUtils.format(r.getStartTime(), DateUtils.FORMAT_DATE_8));
                    rentBillVO.setEndTime(DateUtils.format(r.getEndTime(), DateUtils.FORMAT_DATE_8));
                    rentBillVO.setShouldPayTime(r.getShouldPayTime() == null ? null : DateUtils.format(r.getShouldPayTime(), DateUtils.FORMAT_DATE_8));
                    rentBillVO.setCost(ConvertUtils.fen2yuan(r.getCost()));
                    rentBillVOList.add(rentBillVO);
                });

                map.put("estateExpenseBillVOList", expenseBillVOList);
                map.put("estateRentBillList", rentBillVOList);
                map.put("commission", commission);
            } else {
                //其他费用
                String sql = "select b.* from saas_estate_expense_bill b WHERE 1 = 1 and house_id = ? and payment_status = 0 and audit_status = 1";
                List<Object> args = new ArrayList<>();
                args.add(houseId);
                estateExpenseBillVOList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(EstateExpenseBillVO.class), args.toArray());

                for (EstateExpenseBillVO e : estateExpenseBillVOList) {
                    e.setStartTime(DateUtils.format(e.getStartTime(), DateUtils.FORMAT_DATE_8, DateUtils.FORMAT_DATE_8));
                    e.setEndTime(DateUtils.format(e.getEndTime(), DateUtils.FORMAT_DATE_8, DateUtils.FORMAT_DATE_8));
                    e.setShouldPayTime(StringUtils.isBlank(e.getShouldPayTime()) ? "" : DateUtils.format(e.getShouldPayTime(), DateUtils.FORMAT_DATE_8, DateUtils.FORMAT_DATE_8));
                    e.setCost(ConvertUtils.fen2yuan(Integer.parseInt(e.getCost().toString())));
                    String sql2 = "select b.* from saas_estate_expense_bill_detail b where b.expense_bill_id = " + e.getId();
                    List<EstateExpenseBillDetailVO> detailVOList = jdbcTemplate.query(sql2, new BeanPropertyRowMapper<>(EstateExpenseBillDetailVO.class));
                    if (detailVOList.size() > 0) {
                        EstateExpenseBillDetailVO detailVO = detailVOList.get(0);
                        if (detailVO.getWaterUnitPrice() != null) {
                            detailVO.setWaterUnitPrice(ConvertUtils.fen2yuan(Integer.parseInt(detailVO.getWaterUnitPrice().toString())));
                        }
                        if (detailVO.getElectricUnitPrice() != null) {
                            detailVO.setElectricUnitPrice(ConvertUtils.fen2yuan(Integer.parseInt(detailVO.getElectricUnitPrice().toString())));
                        }
                        if (detailVO.getGasUnitPrice() != null) {
                            detailVO.setGasUnitPrice(ConvertUtils.fen2yuan(Integer.parseInt(detailVO.getGasUnitPrice().toString())));
                        }
                        if (detailVO.getHeatingBill() != null) {
                            detailVO.setHeatingBill(ConvertUtils.fen2yuan(Integer.parseInt(detailVO.getHeatingBill().toString())));
                        }
                        if (detailVO.getPropertyFee() != null) {
                            detailVO.setPropertyFee(ConvertUtils.fen2yuan(Integer.parseInt(detailVO.getPropertyFee().toString())));
                        }
                        if (detailVO.getTvFee() != null) {
                            detailVO.setTvFee(ConvertUtils.fen2yuan(Integer.parseInt(detailVO.getTvFee().toString())));
                        }
                        if (detailVO.getBroadBandCharges() != null) {
                            detailVO.setBroadBandCharges(ConvertUtils.fen2yuan(Integer.parseInt(detailVO.getBroadBandCharges().toString())));
                        }
                        e.setHouseWaitPaymentDetail(detailVO);
                    }
                }

                // 物业房产-租金/押金账单明细
                List<EstateRentBill> estateRentBillList = estateRentBillRepository.findByHouseIdAndPaymentStatusAndAuditStatus(houseId, 0, 1);
                estateRentBillList.forEach(r -> {
                    RentBillVO rentBillVO = new RentBillVO();
                    BeanUtils.copyProperties(r, rentBillVO);
                    rentBillVO.setStartTime(DateUtils.format(r.getStartTime(), DateUtils.FORMAT_DATE_8));
                    rentBillVO.setEndTime(DateUtils.format(r.getEndTime(), DateUtils.FORMAT_DATE_8));
                    rentBillVO.setShouldPayTime(r.getShouldPayTime() == null ? null : DateUtils.format(r.getShouldPayTime(), DateUtils.FORMAT_DATE_8));
                    rentBillVO.setCost(ConvertUtils.fen2yuan(r.getCost()));
                    estateRentBillVOList.add(rentBillVO);
                });

                map.put("estateExpenseBillVOList", estateExpenseBillVOList);
                map.put("estateRentBillList", estateRentBillVOList);
                map.put("commission", commission);
            }

            return ResultBean.successfulResult(map);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }*/

    public ResultBean<Object> relatedHousesPayPage(String accessToken, String houseId, Integer type) {
        try {
            if (StringUtils.isBlank(houseId)) {
                return ResultBean.failedResultWithMsg("房屋id不能为空");
            }
            if (type == null) {
                return ResultBean.failedResultWithMsg("房屋类型不能为空");
            }

            Map<String, Object> map = new HashMap<>();
            List<ExpenseBillVO> expenseBillVOList = new ArrayList<>();
            List<RentBillVO> rentBillVOList = new ArrayList<>();

            List<EstateExpenseBillVO> estateExpenseBillVOList = new ArrayList<>();
            List<RentBillVO> estateRentBillVOList = new ArrayList<>();

            // 手续费比例
            String platStr = redisService.getValue("platform.commission");
            BigDecimal commission = DataUtils.IntegerToBigdecimal(Integer.valueOf(platStr));

            // 房屋类型：1公租房 2物业房产
            if (type.equals(1)) {
                //公租房其他费用
                List<ExpenseBill> expenseBillList = expenseBillRepository.findByHouseIdAndPaymentStatusAndAuditStatus(houseId, 0, 1);
                expenseBillList.forEach(e -> {
                    ExpenseBillVO expenseBillVO = new ExpenseBillVO();
                    BeanUtils.copyProperties(e, expenseBillVO);
                    expenseBillVO.setStartTime(DateUtils.format(e.getStartTime(), DateUtils.FORMAT_DATE_8));
                    expenseBillVO.setEndTime(DateUtils.format(e.getEndTime(), DateUtils.FORMAT_DATE_8));
                    expenseBillVO.setShouldPayTime(e.getShouldPayTime() == null ? null : DateUtils.format(e.getShouldPayTime(), DateUtils.FORMAT_DATE_8));
                    expenseBillVO.setCost(ConvertUtils.fen2yuan(e.getCost()));
                    expenseBillVO.setType(1);
                    expenseBillVOList.add(expenseBillVO);
                });
                //物业其他费用
                List<EstateExpenseBill> expenseBillList2 = estateExpenseBillRepository.findByHouseIdAndPaymentStatusAndAuditStatus(houseId, 0, 1);
                expenseBillList2.forEach(e -> {
                    ExpenseBillVO expenseBillVO = new ExpenseBillVO();
                    BeanUtils.copyProperties(e, expenseBillVO);
                    expenseBillVO.setStartTime(DateUtils.format(e.getStartTime(), DateUtils.FORMAT_DATE_8));
                    expenseBillVO.setEndTime(DateUtils.format(e.getEndTime(), DateUtils.FORMAT_DATE_8));
                    expenseBillVO.setShouldPayTime(e.getShouldPayTime() == null ? null : DateUtils.format(e.getShouldPayTime(), DateUtils.FORMAT_DATE_8));
                    expenseBillVO.setCost(ConvertUtils.fen2yuan(e.getCost()));
                    expenseBillVO.setType(2);
                    expenseBillVOList.add(expenseBillVO);
                });

                for (ExpenseBillVO expenseBillVO : expenseBillVOList) {
                    if (expenseBillVO.getType() == 1) {
                        List<HouseWaitPaymentDetail> houseWaitPaymentDetailList = houseWaitPaymentDetailRepository.findByExpenseBillId(expenseBillVO.getId());
                        if (houseWaitPaymentDetailList.size() > 0) {
                            HouseWaitPaymentDetail detail = houseWaitPaymentDetailList.get(0);
                            HouseWaitPaymentDetailVO detailVO = new HouseWaitPaymentDetailVO();
                            BeanUtils.copyProperties(detail, detailVO);
                            if (detail.getWaterUnitPrice() != null) {
                                detailVO.setWaterUnitPrice(ConvertUtils.fen2yuan(detail.getWaterUnitPrice()));
                            }
                            if (detail.getElectricUnitPrice() != null) {
                                detailVO.setElectricUnitPrice(ConvertUtils.fen2yuan(detail.getElectricUnitPrice()));
                            }
                            if (detail.getGasUnitPrice() != null) {
                                detailVO.setGasUnitPrice(ConvertUtils.fen2yuan(detail.getGasUnitPrice()));
                            }
                            if (detail.getHeatingBill() != null) {
                                detailVO.setHeatingBill(ConvertUtils.fen2yuan(detail.getHeatingBill()));
                            }
                            if (detail.getPropertyFee() != null) {
                                detailVO.setPropertyFee(ConvertUtils.fen2yuan(detail.getPropertyFee()));
                            }
                            if (detail.getTvFee() != null) {
                                detailVO.setTvFee(ConvertUtils.fen2yuan(detail.getTvFee()));
                            }
                            if (detail.getBroadBandCharges() != null) {
                                detailVO.setBroadBandCharges(ConvertUtils.fen2yuan(detail.getBroadBandCharges()));
                            }
                            expenseBillVO.setHouseWaitPaymentDetail(detailVO);
                        }
                    } else {
                        EstateExpenseBillDetail detail = estateExpenseBillDetailRepository.findByExpenseBillId(expenseBillVO.getId());
                        if (detail != null) {
                            HouseWaitPaymentDetailVO detailVO = new HouseWaitPaymentDetailVO();
                            BeanUtils.copyProperties(detail, detailVO);
                            if (detail.getWaterUnitPrice() != null) {
                                detailVO.setWaterUnitPrice(ConvertUtils.fen2yuan(detail.getWaterUnitPrice()));
                            }
                            if (detail.getElectricUnitPrice() != null) {
                                detailVO.setElectricUnitPrice(ConvertUtils.fen2yuan(detail.getElectricUnitPrice()));
                            }
                            if (detail.getGasUnitPrice() != null) {
                                detailVO.setGasUnitPrice(ConvertUtils.fen2yuan(detail.getGasUnitPrice()));
                            }
                            if (detail.getHeatingBill() != null) {
                                detailVO.setHeatingBill(ConvertUtils.fen2yuan(detail.getHeatingBill()));
                            }
                            if (detail.getPropertyFee() != null) {
                                detailVO.setPropertyFee(ConvertUtils.fen2yuan(detail.getPropertyFee()));
                            }
                            if (detail.getTvFee() != null) {
                                detailVO.setTvFee(ConvertUtils.fen2yuan(detail.getTvFee()));
                            }
                            if (detail.getBroadBandCharges() != null) {
                                detailVO.setBroadBandCharges(ConvertUtils.fen2yuan(detail.getBroadBandCharges()));
                            }
                            expenseBillVO.setHouseWaitPaymentDetail(detailVO);
                        }
                    }
                }

                // 公租房-租金/押金账单明细
                List<RentBill> rentBillList = rentBillRepository.findByHouseIdAndPaymentStatusAndAuditStatus(houseId, 0, 1);
                rentBillList.forEach(r -> {
                    RentBillVO rentBillVO = new RentBillVO();
                    BeanUtils.copyProperties(r, rentBillVO);
                    rentBillVO.setStartTime(DateUtils.format(r.getStartTime(), DateUtils.FORMAT_DATE_8));
                    rentBillVO.setEndTime(DateUtils.format(r.getEndTime(), DateUtils.FORMAT_DATE_8));
                    rentBillVO.setShouldPayTime(r.getShouldPayTime() == null ? null : DateUtils.format(r.getShouldPayTime(), DateUtils.FORMAT_DATE_8));
                    rentBillVO.setCost(ConvertUtils.fen2yuan(r.getCost()));
                    rentBillVO.setType(1);
                    rentBillVOList.add(rentBillVO);
                });
                // 物业房产-租金/押金账单明细
                List<EstateRentBill> estateRentBillList = estateRentBillRepository.findByHouseIdAndPaymentStatusAndAuditStatus(houseId, 0, 1);
                estateRentBillList.forEach(r -> {
                    RentBillVO rentBillVO = new RentBillVO();
                    BeanUtils.copyProperties(r, rentBillVO);
                    rentBillVO.setStartTime(DateUtils.format(r.getStartTime(), DateUtils.FORMAT_DATE_8));
                    rentBillVO.setEndTime(DateUtils.format(r.getEndTime(), DateUtils.FORMAT_DATE_8));
                    rentBillVO.setShouldPayTime(r.getShouldPayTime() == null ? null : DateUtils.format(r.getShouldPayTime(), DateUtils.FORMAT_DATE_8));
                    rentBillVO.setCost(ConvertUtils.fen2yuan(r.getCost()));
                    rentBillVO.setType(2);
                    estateRentBillVOList.add(rentBillVO);
                });

                map.put("estateExpenseBillVOList", expenseBillVOList);
                map.put("estateRentBillList", rentBillVOList);
                map.put("commission", commission);
            } else {
                //其他费用
                String sql = "select b.* from saas_estate_expense_bill b WHERE 1 = 1 and house_id = ? and payment_status = 0 and audit_status = 1";
                List<Object> args = new ArrayList<>();
                args.add(houseId);
                estateExpenseBillVOList = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(EstateExpenseBillVO.class), args.toArray());

                for (EstateExpenseBillVO e : estateExpenseBillVOList) {
                    e.setStartTime(DateUtils.format(e.getStartTime(), DateUtils.FORMAT_DATE_8, DateUtils.FORMAT_DATE_8));
                    e.setEndTime(DateUtils.format(e.getEndTime(), DateUtils.FORMAT_DATE_8, DateUtils.FORMAT_DATE_8));
                    e.setShouldPayTime(StringUtils.isBlank(e.getShouldPayTime()) ? "" : DateUtils.format(e.getShouldPayTime(), DateUtils.FORMAT_DATE_8, DateUtils.FORMAT_DATE_8));
                    e.setCost(ConvertUtils.fen2yuan(Integer.parseInt(e.getCost().toString())));
                    e.setType(2);
                    String sql2 = "select b.* from saas_estate_expense_bill_detail b where b.expense_bill_id = " + e.getId();
                    List<EstateExpenseBillDetailVO> detailVOList = jdbcTemplate.query(sql2, new BeanPropertyRowMapper<>(EstateExpenseBillDetailVO.class));
                    if (detailVOList.size() > 0) {
                        EstateExpenseBillDetailVO detailVO = detailVOList.get(0);
                        if (detailVO.getWaterUnitPrice() != null) {
                            detailVO.setWaterUnitPrice(ConvertUtils.fen2yuan(Integer.parseInt(detailVO.getWaterUnitPrice().toString())));
                        }
                        if (detailVO.getElectricUnitPrice() != null) {
                            detailVO.setElectricUnitPrice(ConvertUtils.fen2yuan(Integer.parseInt(detailVO.getElectricUnitPrice().toString())));
                        }
                        if (detailVO.getGasUnitPrice() != null) {
                            detailVO.setGasUnitPrice(ConvertUtils.fen2yuan(Integer.parseInt(detailVO.getGasUnitPrice().toString())));
                        }
                        if (detailVO.getHeatingBill() != null) {
                            detailVO.setHeatingBill(ConvertUtils.fen2yuan(Integer.parseInt(detailVO.getHeatingBill().toString())));
                        }
                        if (detailVO.getPropertyFee() != null) {
                            detailVO.setPropertyFee(ConvertUtils.fen2yuan(Integer.parseInt(detailVO.getPropertyFee().toString())));
                        }
                        if (detailVO.getTvFee() != null) {
                            detailVO.setTvFee(ConvertUtils.fen2yuan(Integer.parseInt(detailVO.getTvFee().toString())));
                        }
                        if (detailVO.getBroadBandCharges() != null) {
                            detailVO.setBroadBandCharges(ConvertUtils.fen2yuan(Integer.parseInt(detailVO.getBroadBandCharges().toString())));
                        }
                        e.setHouseWaitPaymentDetail(detailVO);
                    }
                }

                // 物业房产-租金/押金账单明细
                List<EstateRentBill> estateRentBillList = estateRentBillRepository.findByHouseIdAndPaymentStatusAndAuditStatus(houseId, 0, 1);
                estateRentBillList.forEach(r -> {
                    RentBillVO rentBillVO = new RentBillVO();
                    BeanUtils.copyProperties(r, rentBillVO);
                    rentBillVO.setStartTime(DateUtils.format(r.getStartTime(), DateUtils.FORMAT_DATE_8));
                    rentBillVO.setEndTime(DateUtils.format(r.getEndTime(), DateUtils.FORMAT_DATE_8));
                    rentBillVO.setShouldPayTime(r.getShouldPayTime() == null ? null : DateUtils.format(r.getShouldPayTime(), DateUtils.FORMAT_DATE_8));
                    rentBillVO.setCost(ConvertUtils.fen2yuan(r.getCost()));
                    rentBillVO.setType(2);
                    estateRentBillVOList.add(rentBillVO);
                });

                map.put("estateExpenseBillVOList", estateExpenseBillVOList);
                map.put("estateRentBillList", estateRentBillVOList);
                map.put("commission", commission);
            }

            return ResultBean.successfulResult(map);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    public ResultBean<Object> allBillsPage(String accessToken) {

        return ResultBean.successfulResult(null);
    }

    public ResultBean<Object> findCommunity(String accessToken, Long area) {
        LOG.info("lifePayService findCommunity  accessToken={} , area={} ", accessToken, area);

        if (area == null) {
            return ResultBean.failedResultWithMsg("区域不能为空");
        }

        List<Community> communityList = communityRepository.findByCityIdAndStatus(area, 1);
        return ResultBean.successfulResult(communityList);
    }

    public ResultBean<List<String>> findRoomNumber(String communityId, Long buildId, Long unitId) {
        LOG.info("findRoomNumber communityId={}, buildId={}, unitId={}",communityId,buildId,unitId);
        List<House> houseList = houseRepository.findByResidenceCommunityIdAndBuildingNumAndUnitOrderByRoomNumber(communityId, buildId, unitId);

        List<String> list = new ArrayList<>();
        houseList.forEach(house -> {
            list.add(house.getRoomNumber());
        });

        return ResultBean.successfulResult(list);
    }

    /*public ResultBean<Map<String, Object>> payment(String accessToken, RentBillPaymentVo vo) {
        try {
            LOG.info("LifePayService payment vo={}", vo.toString());

            if (CollectionUtils.isEmpty(vo.getIds()) && CollectionUtils.isEmpty(vo.getExpenseIds())) {
                return ResultBean.failedResultOfParamWithMsg("参数错误");
            }
            if (vo.getPaymentMode() == null || vo.getPaymentType() == null || vo.getChargeType() == null) {
                return ResultBean.failedResultOfParamWithMsg("参数错误");
            }
            if (!PaymentTypeEnum.operate(vo.getPaymentType()) || !PaymentModeEnum.operate(vo.getPaymentMode())
                    || !ChargeTypeEnum.operate(vo.getChargeType())) {
                return ResultBean.failedResultOfParamWithMsg("参数错误");
            }

            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();

            Integer cose = 0;
            Long orgId = null;
            if (vo.getType() == 1) {
                List<RentBill> rentBills = new ArrayList<>();
                List<ExpenseBill> expenseBills = new ArrayList<>();
                if (!CollectionUtils.isEmpty(vo.getIds())) {
                    rentBills = rentBillRepository.findByIdIn(vo.getIds());
                }
                if (!CollectionUtils.isEmpty(vo.getExpenseIds())) {
                    expenseBills = expenseBillRepository.findByIdIn(vo.getExpenseIds());
                }

                if (CollectionUtils.isEmpty(rentBills) && CollectionUtils.isEmpty(expenseBills)) {
                    LOG.warn("LifePayService payment 未找到费用明细 id={}", vo.getIds());
                    return ResultBean.failedResultWithMsg("未找到费用明细，请重试");
                }

                for (RentBill rentBill : rentBills) {
                    if (rentBill.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                        LOG.warn("LifePayService payment 此费用已支付,无需重复支付 id={},houseId={}", rentBill.getId(), rentBill.getHouseId());
                        return ResultBean.failedResultWithMsg("当前有费用已支付,无需重复支付");
                    }
                    cose += rentBill.getCost();
                }
                for (ExpenseBill expenseBill : expenseBills) {
                    if (expenseBill.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                        LOG.warn("LifePayService payment 此费用已支付,无需重复支付 id={},houseId={}", expenseBill.getId(), expenseBill.getHouseId());
                        return ResultBean.failedResultWithMsg("当前有费用已支付,无需重复支付");
                    }
                    cose += expenseBill.getCost();
                }

                if (!rentBills.isEmpty()) {
                    orgId = rentBills.get(0).getOrgId();
                }
                if (!expenseBills.isEmpty()) {
                    orgId = expenseBills.get(0).getOrgId();
                }
            }

            if (vo.getType() == 2) {
                List<EstateRentBill> estateRentBills = new ArrayList<>();
                List<EstateExpenseBill> estateExpenseBills = new ArrayList<>();
                if (!CollectionUtils.isEmpty(vo.getIds())) {
                    estateRentBills = estateRentBillRepository.findByIdIn(vo.getIds());
                }
                if (!CollectionUtils.isEmpty(vo.getExpenseIds())) {
                    estateExpenseBills = estateExpenseBillRepository.findByIdIn(vo.getExpenseIds());
                }

                if (CollectionUtils.isEmpty(estateRentBills) && CollectionUtils.isEmpty(estateExpenseBills)) {
                    LOG.warn("LifePayService payment 未找到费用明细 id={}", vo.getIds());
                    return ResultBean.failedResultWithMsg("未找到费用明细，请重试");
                }

                for (EstateRentBill estateRentBill : estateRentBills) {
                    if (estateRentBill.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                        LOG.warn("LifePayService payment 此费用已支付,无需重复支付 id={},houseId={}", estateRentBill.getId(), estateRentBill.getHouseId());
                        return ResultBean.failedResultWithMsg("当前有费用已支付,无需重复支付");
                    }
                    cose += estateRentBill.getCost();
                }
                for (EstateExpenseBill estateExpenseBill : estateExpenseBills) {
                    if (estateExpenseBill.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                        LOG.warn("LifePayService payment 此费用已支付,无需重复支付 id={},houseId={}", estateExpenseBill.getId(), estateExpenseBill.getHouseId());
                        return ResultBean.failedResultWithMsg("当前有费用已支付,无需重复支付");
                    }
                    cose += estateExpenseBill.getCost();
                }

                if (!estateRentBills.isEmpty()) {
                    orgId = estateRentBills.get(0).getOrgId();
                }
                if (!estateExpenseBills.isEmpty()) {
                    orgId = estateExpenseBills.get(0).getOrgId();
                }
            }

            // 手续费比例
            String platStr = redisService.getValue("platform.commission");
            BigDecimal totalAmount = DataUtils.IntegerToBigdecimal(cose);
            Integer plat = 0;
            if (StringUtils.isNotBlank(platStr)) {
                BigDecimal platform = DataUtils.IntegerToBigdecimal(Integer.valueOf(platStr));
                BigDecimal platAmount = totalAmount.multiply(platform).setScale(2, BigDecimal.ROUND_HALF_UP);
                totalAmount = totalAmount.add(platAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
                plat = DataUtils.doubleToInteger(platAmount.doubleValue());
            }

            String outTradeNo = String.valueOf(KeyWorker.nextId());
            PaymentBillRedisVo redisVo = new PaymentBillRedisVo();
            redisVo.setOrgId(orgId);
            redisVo.setPaymentMode(vo.getPaymentMode());
            redisVo.setPaymentStatus(0);
            redisVo.setPlat(plat);
            redisVo.setUserId(userId);
            redisVo.setOutTradeNo(outTradeNo);
            redisVo.setIds(vo.getIds());
            redisVo.setExpenseIds(vo.getExpenseIds());
            redisVo.setType(vo.getType());
            redisVo.setTotalAmount(totalAmount);
            redisVo.setBusinessType(5);//生活缴费

            // 操作用户企业信息
            DepartmentHierarchy departmentHierarchy = departmentHierarchyService.getEnterpriseInfo(orgId);
            if (departmentHierarchy == null) {
                LOG.warn("LifePayService payment 未找到您当前所在机构/企业 userId={},orgId={}", userId, orgId);
                return ResultBean.failedResultWithMsg("企业信息错误");
            }

            //0元支付
            if (DataUtils.doubleToInteger(totalAmount.doubleValue()) == 0) {
                return zeroPayment(redisVo);
            }

            //商品标题
            String body = "";
            if (!CollectionUtils.isEmpty(vo.getIds()) && CollectionUtils.isEmpty(vo.getExpenseIds())) {
                if (vo.getIds().size() == 1) {
                    Integer chargeType = null;
                    if (vo.getType() == 1) {
                        List<RentBill> rentBills = rentBillRepository.findByIdIn(vo.getIds());
                        chargeType = rentBills.get(0).getChargeType();
                    } else {
                        List<EstateRentBill> estateRentBills = estateRentBillRepository.findByIdIn(vo.getIds());
                        chargeType = estateRentBills.get(0).getChargeType();
                    }
                    body = "房屋管家-" + ChargeTypeEnum.getText(chargeType);
                } else {
                    body = "房屋管家-租金/押金组合支付";
                }
            }

            if (CollectionUtils.isEmpty(vo.getIds()) && !CollectionUtils.isEmpty(vo.getExpenseIds())) {
                if (vo.getExpenseIds().size() == 1) {
                    Integer chargeType = null;
                    if (vo.getType() == 1) {
                        List<ExpenseBill> expenseBills = expenseBillRepository.findByIdIn(vo.getExpenseIds());
                        chargeType = expenseBills.get(0).getChargeType();
                    } else {
                        List<EstateExpenseBill> estateExpenseBills = estateExpenseBillRepository.findByIdIn(vo.getExpenseIds());
                        chargeType = estateExpenseBills.get(0).getChargeType();
                    }
                    // 其它费用类型转换
                    String chargeTypeName = "";
                    if (chargeType == 1) {
                        chargeTypeName = "水费";
                    } else if (chargeType == 2) {
                        chargeTypeName = "电费";
                    } else if (chargeType == 3) {
                        chargeTypeName = "物业费";
                    } else if (chargeType == 4) {
                        chargeTypeName = "宽带费";
                    } else if (chargeType == 5) {
                        chargeTypeName = "电视费";
                    } else if (chargeType == 6) {
                        chargeTypeName = "煤气费";
                    } else if (chargeType == 7) {
                        chargeTypeName = "暖气费";
                    }
                    body = "房屋管家-" + chargeTypeName;
                } else {
                    body = "房屋管家-其他费用组合支付";
                }
            }

            if (!CollectionUtils.isEmpty(vo.getIds()) && !CollectionUtils.isEmpty(vo.getExpenseIds())) {
                body = "房屋管家-租金/其他费用组合支付";
            }

            // 支付方式
            if (vo.getPaymentType() == PaymentTypeEnum.WECHAT.getValue()) {
                WechatAccount account = null;
                // 根据企业设置, 获取收款方式(平台收款, 企业商户号收款)
                // 收款方式：0平台商户号收款 1企业商户号收款
                if (departmentHierarchy.getMerchantsType() == 0) {
                    // 0为平台收款商户号企业id
                    account = wechatAccountRepository.findByOrgIdAndType(0L, PaymentTypeEnum.WECHAT.getValue());
                } else {
                    // 默认使用企业账户号收款
                    account = wechatAccountRepository.findByOrgIdAndType(orgId, PaymentTypeEnum.WECHAT.getValue());
                }

                if (account == null) {
                    LOG.warn("LifePayService payment 未找到微信商户配置,请联系负责人orgId={}", orgId);
                    return ResultBean.failedResultWithMsg("未找到微信商户配置,请联系客服");
                }

                //应用ID或者分配的appId
                String appId = redisService.getValue(Constant.WX_APPID);
                String attac = outTradeNo;
                String spbillCreateIp = redisService.getValue(Constant.SPBILL_CREATE_IP);

                cose = DataUtils.doubleToInteger(totalAmount.doubleValue());

                WxPay wxpay = new WxPay(appId, account.getMchId(), outTradeNo, attac, cose, body,
                        account.getMchApiKey(), null, payConfig.getWxNotifyUrl(), payConfig.getUnifiedApi(), spbillCreateIp);
                Map<String, Object> result = new WxPayRequest(wxpay).unifiedByApp();
                if (result == null) {
                    return ResultBean.failedResultWithMsg("微信支付异常,请联系客服");
                }

                redisVo.setMchApiKey(account.getMchApiKey());
                redisVo.setMerchantId(account.getId());
                redisVo.setMerchantsType(departmentHierarchy.getMerchantsType());
                redisService.putPaymentBill(redisVo);
                return ResultBean.successfulResult(result);
            }

            if (vo.getPaymentType() == PaymentTypeEnum.ALI.getValue()) {
                WechatAccount account = null;
                // 收款方式：0平台商户号收款 1企业商户号收款
                if (departmentHierarchy.getMerchantsType() == 0) {
                    // 0为平台收款商户号企业id
                    account = wechatAccountRepository.findByOrgIdAndType(0L, PaymentTypeEnum.ALI.getValue());
                } else {
                    // 默认使用企业账户号收款
                    account = wechatAccountRepository.findByOrgIdAndType(orgId, PaymentTypeEnum.ALI.getValue());
                }

                if (account == null) {
                    LOG.warn("LifePayService payment 未找到支付宝配置,请联系负责人 orgId={}", orgId);
                    return ResultBean.failedResultWithMsg("未找到支付宝配置,请联系负责人");
                }

                //String subject = ChargeTypeEnum.getText(vo.getChargeType());
                String passbackParams = outTradeNo;
                AliPay alipay = new AliPay(account.getMchId(), account.getPrivateKey(), account.getPublicKey(),
                        outTradeNo, totalAmount.toString(), body, "QUICK_MSECURITY_PAY", passbackParams,
                        payConfig.getAliNotifyUrl());
                Map<String, Object> result = new AliPayRequest(alipay).appPay();
                if (result == null) {
                    return ResultBean.failedResultWithMsg("支付宝支付异常,请联系客服");
                }

                redisVo.setPublicKey(account.getPublicKey());
                redisVo.setMerchantId(account.getId());
                redisVo.setMerchantsType(departmentHierarchy.getMerchantsType());
                redisService.putPaymentBill(redisVo);
                return ResultBean.successfulResult(result);
            }

            return ResultBean.failedResultOfParamWithMsg("参数错误");
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }*/

    public ResultBean<Map<String, Object>> payment(String accessToken, RentBillPaymentVo vo) {
        try {
            LOG.info("LifePayService payment vo={}", vo.toString());

            if (CollectionUtils.isEmpty(vo.getRentIds()) && CollectionUtils.isEmpty(vo.getExpenseIds())
                    && CollectionUtils.isEmpty(vo.getEstateRentIds()) && CollectionUtils.isEmpty(vo.getEstateExpenseIds())) {
                return ResultBean.failedResultOfParamWithMsg("参数错误");
            }
            if (vo.getPaymentMode() == null || vo.getPaymentType() == null || vo.getChargeType() == null) {
                return ResultBean.failedResultOfParamWithMsg("参数错误");
            }
            if (!PaymentTypeEnum.operate(vo.getPaymentType()) || !PaymentModeEnum.operate(vo.getPaymentMode())
                    || !ChargeTypeEnum.operate(vo.getChargeType())) {
                return ResultBean.failedResultOfParamWithMsg("参数错误");
            }

            TokenRedisVo tokenRedisVo = redisService.findTokenVo(accessToken);
            if (tokenRedisVo == null) {
                return ResultBean.failedResultOfToken();
            }
            String userId = tokenRedisVo.getId();

            Integer cose = 0;
            Long orgId = null;

            List<RentBill> rentBills = new ArrayList<>();
            List<ExpenseBill> expenseBills = new ArrayList<>();
            List<EstateRentBill> estateRentBills = new ArrayList<>();
            List<EstateExpenseBill> estateExpenseBills = new ArrayList<>();
            if (!CollectionUtils.isEmpty(vo.getRentIds())) {
                rentBills = rentBillRepository.findByIdIn(vo.getRentIds());
            }
            if (!CollectionUtils.isEmpty(vo.getExpenseIds())) {
                expenseBills = expenseBillRepository.findByIdIn(vo.getExpenseIds());
            }
            if (!CollectionUtils.isEmpty(vo.getEstateRentIds())) {
                estateRentBills = estateRentBillRepository.findByIdIn(vo.getEstateRentIds());
            }
            if (!CollectionUtils.isEmpty(vo.getEstateExpenseIds())) {
                estateExpenseBills = estateExpenseBillRepository.findByIdIn(vo.getEstateExpenseIds());
            }

            if (CollectionUtils.isEmpty(rentBills) && CollectionUtils.isEmpty(expenseBills)
                    && CollectionUtils.isEmpty(estateRentBills) && CollectionUtils.isEmpty(estateExpenseBills)) {
                LOG.warn("AioService payment 未找到费用明细 rentIds={},expenseIds={},estateRentIds={},estateExpenseIds={}",
                        vo.getRentIds(), vo.getExpenseIds(), vo.getEstateRentIds(), vo.getEstateExpenseIds());
                return ResultBean.failedResultWithMsg("未找到费用明细，请重试");
            }

            for (RentBill rentBill : rentBills) {
                if (rentBill.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                    LOG.warn("AioService payment 此费用已支付,无需重复支付 id={},houseId={}", rentBill.getId(), rentBill.getHouseId());
                    return ResultBean.failedResultWithMsg("当前有费用已支付,无需重复支付");
                }
                cose += rentBill.getCost();
            }
            for (ExpenseBill expenseBill : expenseBills) {
                if (expenseBill.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                    LOG.warn("AioService payment 此费用已支付,无需重复支付 id={},houseId={}", expenseBill.getId(), expenseBill.getHouseId());
                    return ResultBean.failedResultWithMsg("当前有费用已支付,无需重复支付");
                }
                cose += expenseBill.getCost();
            }
            for (EstateRentBill estateRentBill : estateRentBills) {
                if (estateRentBill.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                    LOG.warn("AioService payment 此费用已支付,无需重复支付 id={},houseId={}", estateRentBill.getId(), estateRentBill.getHouseId());
                    return ResultBean.failedResultWithMsg("当前有费用已支付,无需重复支付");
                }
                cose += estateRentBill.getCost();
            }
            for (EstateExpenseBill estateExpenseBill : estateExpenseBills) {
                if (estateExpenseBill.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                    LOG.warn("AioService payment 此费用已支付,无需重复支付 id={},houseId={}", estateExpenseBill.getId(), estateExpenseBill.getHouseId());
                    return ResultBean.failedResultWithMsg("当前有费用已支付,无需重复支付");
                }
                cose += estateExpenseBill.getCost();
            }

            if (!CollectionUtils.isEmpty(rentBills)) {
                orgId = rentBills.get(0).getOrgId();
            }
            if (!CollectionUtils.isEmpty(expenseBills)) {
                orgId = expenseBills.get(0).getOrgId();
            }
            if (!CollectionUtils.isEmpty(estateRentBills)) {
                orgId = estateRentBills.get(0).getOrgId();
            }
            if (!CollectionUtils.isEmpty(estateExpenseBills)) {
                orgId = estateExpenseBills.get(0).getOrgId();
            }

            // 手续费比例
            String platStr = redisService.getValue("platform.commission");
            BigDecimal totalAmount = DataUtils.IntegerToBigdecimal(cose);
            Integer plat = 0;
            if (StringUtils.isNotBlank(platStr)) {
                BigDecimal platform = DataUtils.IntegerToBigdecimal(Integer.valueOf(platStr));
                BigDecimal platAmount = totalAmount.multiply(platform).setScale(2, BigDecimal.ROUND_HALF_UP);
                totalAmount = totalAmount.add(platAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
                plat = DataUtils.doubleToInteger(platAmount.doubleValue());
            }

            String outTradeNo = String.valueOf(KeyWorker.nextId());
            PaymentBillRedisVo redisVo = new PaymentBillRedisVo();
            redisVo.setOrgId(orgId);
            redisVo.setPaymentMode(vo.getPaymentMode());
            redisVo.setPaymentStatus(0);
            redisVo.setPlat(plat);
            redisVo.setUserId(userId);
            redisVo.setOutTradeNo(outTradeNo);
            redisVo.setIds(vo.getRentIds());
            redisVo.setExpenseIds(vo.getExpenseIds());
            redisVo.setEstateRentIds(vo.getEstateRentIds());
            redisVo.setEstateExpenseIds(vo.getEstateExpenseIds());
            redisVo.setType(vo.getType());
            redisVo.setTotalAmount(totalAmount);
            redisVo.setBusinessType(5);//生活缴费

            //企业信息
            DepartmentHierarchy departmentHierarchy = departmentHierarchyService.getEnterpriseInfo(orgId);
            if (departmentHierarchy == null) {
                LOG.warn("LifePayService payment 企业信息错误, orgId={}", orgId);
                return ResultBean.failedResultWithMsg("企业信息错误");
            }

            //0元支付
            if (DataUtils.doubleToInteger(totalAmount.doubleValue()) == 0) {
                return zeroPayment(redisVo);
            }

            //商品标题
            String body = "房屋管家-生活缴费支付";
            // 支付方式
            if (vo.getPaymentType() == PaymentTypeEnum.WECHAT.getValue()) {
                WechatAccount account = null;
                // 根据企业设置, 获取收款方式(平台收款, 企业商户号收款)
                // 收款方式：0平台商户号收款 1企业商户号收款
                if (departmentHierarchy.getMerchantsType() == 0) {
                    // 0为平台收款商户号企业id
                    account = wechatAccountRepository.findByOrgIdAndType(0L, PaymentTypeEnum.WECHAT.getValue());
                } else {
                    // 默认使用企业账户号收款
                    account = wechatAccountRepository.findByOrgIdAndType(orgId, PaymentTypeEnum.WECHAT.getValue());
                }

                if (account == null) {
                    LOG.warn("LifePayService payment 未找到微信商户配置,请联系负责人orgId={}", orgId);
                    return ResultBean.failedResultWithMsg("未找到微信商户配置,请联系客服");
                }

                //应用ID或者分配的appId
                String appId = redisService.getValue(Constant.WX_APPID);
                String attac = outTradeNo;
                String spbillCreateIp = redisService.getValue(Constant.SPBILL_CREATE_IP);

                cose = DataUtils.doubleToInteger(totalAmount.doubleValue());

                WxPay wxpay = new WxPay(appId, account.getMchId(), outTradeNo, attac, cose, body,
                        account.getMchApiKey(), null, payConfig.getWxNotifyUrl(), payConfig.getUnifiedApi(), spbillCreateIp);
                Map<String, Object> result = new WxPayRequest(wxpay).unifiedByApp();
                if (result == null) {
                    return ResultBean.failedResultWithMsg("微信支付异常,请联系客服");
                }

                redisVo.setMchApiKey(account.getMchApiKey());
                redisVo.setMerchantId(account.getId());
                redisVo.setMerchantsType(departmentHierarchy.getMerchantsType());
                redisService.putPaymentBill(redisVo);
                return ResultBean.successfulResult(result);
            }

            if (vo.getPaymentType() == PaymentTypeEnum.ALI.getValue()) {
                WechatAccount account = null;
                // 收款方式：0平台商户号收款 1企业商户号收款
                if (departmentHierarchy.getMerchantsType() == 0) {
                    // 0为平台收款商户号企业id
                    account = wechatAccountRepository.findByOrgIdAndType(0L, PaymentTypeEnum.ALI.getValue());
                } else {
                    // 默认使用企业账户号收款
                    account = wechatAccountRepository.findByOrgIdAndType(orgId, PaymentTypeEnum.ALI.getValue());
                }

                if (account == null) {
                    LOG.warn("LifePayService payment 未找到支付宝配置,请联系负责人 orgId={}", orgId);
                    return ResultBean.failedResultWithMsg("未找到支付宝配置,请联系负责人");
                }

                //String subject = ChargeTypeEnum.getText(vo.getChargeType());
                String passbackParams = outTradeNo;
                AliPay alipay = new AliPay(account.getMchId(), account.getPrivateKey(), account.getPublicKey(),
                        outTradeNo, totalAmount.toString(), body, "QUICK_MSECURITY_PAY", passbackParams,
                        payConfig.getAliNotifyUrl());
                Map<String, Object> result = new AliPayRequest(alipay).appPay();
                if (result == null) {
                    return ResultBean.failedResultWithMsg("支付宝支付异常,请联系客服");
                }

                redisVo.setPublicKey(account.getPublicKey());
                redisVo.setMerchantId(account.getId());
                redisVo.setMerchantsType(departmentHierarchy.getMerchantsType());
                redisService.putPaymentBill(redisVo);
                return ResultBean.successfulResult(result);
            }

            return ResultBean.failedResultOfParamWithMsg("参数错误");
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

    /*public ResultBean<Map<String, Object>> zeroPayment(PaymentBillRedisVo redisVo) {
        try {
            ResultBean<Map<String, Object>> resultBean = new ResultBean<>();
            resultBean.setCode("10009");
            resultBean.setMsg("0元支付成功");

            Date payTime = new Date();
            Integer billAmount = 0;

            if (redisVo.getType() == 1) {
                List<RentBill> rentBills = new ArrayList<>();
                List<ExpenseBill> expenseBills = new ArrayList<>();
                if (!CollectionUtils.isEmpty(redisVo.getIds())) {
                    rentBills = rentBillRepository.findByIdIn(redisVo.getIds());
                }
                if (!CollectionUtils.isEmpty(redisVo.getExpenseIds())) {
                    expenseBills = expenseBillRepository.findByIdIn(redisVo.getExpenseIds());
                }

                if (CollectionUtils.isEmpty(rentBills) && CollectionUtils.isEmpty(expenseBills)) {
                    LOG.error("WxPayService handleLifePay<微信app生活缴费账单账单支付回调> 未找到相关费用信息 outTradeNo={}", redisVo.getOutTradeNo());
                    return ResultBean.failedResultWithMsg("未找到相关费用信息");
                }

                LOG.info("WxPayService handleLifePay, redisVo={}, rentBills={}, expenseBills={}", JSON.toJSONString(redisVo), JSON.toJSONString(rentBills),
                        JSON.toJSONString(expenseBills));

                List<HousePaymentOrderRelation> porList = new ArrayList<>();
                for (RentBill b : rentBills) {
                    if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                        continue;
                    }
                    // 修改状态为已缴费
                    b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
                    b.setPaymentTime(payTime);
                    b.setPaymentChannel(1);
                    billAmount += b.getCost();

                    HousePaymentOrderRelation por = new HousePaymentOrderRelation();
                    por.setOrderNumber(redisVo.getOutTradeNo());
                    por.setBillId(b.getId());
                    por.setPlatformCommissionAmount(redisVo.getPlat());
                    //por.setMerchantId(redisVo.getMerchantId());
                    por.setBillAmount(b.getCost());
                    if (b.getChargeType() == 1) {
                        por.setBusinessType(BusinessTypeEnum.RENT_FEE.getValue());
                    } else if (b.getChargeType() == 2) {
                        por.setBusinessType(BusinessTypeEnum.DEPOSIT_FEE.getValue());
                    }
                    porList.add(por);
                }
                rentBillRepository.saveAll(rentBills);

                for (ExpenseBill b : expenseBills) {
                    if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                        continue;
                    }
                    // 修改状态为已缴费
                    b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
                    b.setPaymentTime(payTime);
                    b.setPaymentChannel(1);
                    billAmount += b.getCost();

                    HousePaymentOrderRelation por = new HousePaymentOrderRelation();
                    por.setOrderNumber(redisVo.getOutTradeNo());
                    por.setBillId(b.getId());
                    por.setPlatformCommissionAmount(redisVo.getPlat());
                    //por.setMerchantId(redisVo.getMerchantId());
                    por.setBillAmount(b.getCost());
                    // 其它费用类型转换
                    if (b.getChargeType() == 1) {
                        por.setBusinessType(BusinessTypeEnum.WATER_FEE.getValue());
                    } else if (b.getChargeType() == 2) {
                        por.setBusinessType(BusinessTypeEnum.ELECTRIC_FEE.getValue());
                    } else if (b.getChargeType() == 3) {
                        por.setBusinessType(BusinessTypeEnum.PROPERTY_FEE.getValue());
                    } else if (b.getChargeType() == 4) {
                        por.setBusinessType(BusinessTypeEnum.BROADBAND_FEE.getValue());
                    } else if (b.getChargeType() == 5) {
                        por.setBusinessType(BusinessTypeEnum.TV_FEE.getValue());
                    } else if (b.getChargeType() == 6) {
                        por.setBusinessType(BusinessTypeEnum.COALGAS_FEE.getValue());
                    } else if (b.getChargeType() == 7) {
                        por.setBusinessType(BusinessTypeEnum.HEATING_FEE.getValue());
                    }
                    porList.add(por);
                }
                expenseBillRepository.saveAll(expenseBills);

                housePaymentOrderRelationRepository.saveAll(porList);

                //验证租金、押金是否都支付完成，全部支付完成，才能修改公租房与合同状态
                if (!CollectionUtils.isEmpty(redisVo.getIds())) {
                    // 根据当前支付的账单明细，找到缴费账单对应的所有合同
                    List<RentBillRelation> relationList = rentBillRelationRepository.findByRentBillIdIn(redisVo.getIds());
                    Map<String, String> houseMap = new HashMap<>();
                    List<String> contractNubmers = new ArrayList<>();
                    for (RentBillRelation r : relationList) {
                        houseMap.put(r.getContractNubmer(), r.getHouseId());
                        contractNubmers.add(r.getContractNubmer());
                    }
                    contractNubmers = contractNubmers.stream().distinct().collect(Collectors.toList());
                    // 查询拥有未支付的合同信息
                    List<RentBillRelation> noPayBillList = rentBillRelationRepository.findNoPayBill(contractNubmers);

                    // 保存全部支付完成(租金 + 押金)的合同编号
                    List<String> completedContracts = new ArrayList<>();
                    // 保存全部支付完成的公租房id
                    List<String> houseIds = new ArrayList<>();

                    // 验证合同是否支付完成
                    Map<String, String> map = noPayBillList.stream()
                            .collect(Collectors.toMap(RentBillRelation::getContractNubmer, RentBillRelation::getHouseId));
                    for (String contractNumber : contractNubmers) {
                        String houseId = map.get(contractNumber);
                        if (houseId == null) {
                            completedContracts.add(contractNumber);
                            String sHouseId = houseMap.get(contractNumber);
                            if (StringUtils.isNotBlank(sHouseId)) {
                                houseIds.add(sHouseId);
                            }
                        }
                    }

                    // 更新公租房合同缴费状态
                    if (!houseIds.isEmpty()) {
                        List<House> houseList = houseRepository.findByIdIn(houseIds);
                        houseList.forEach(h -> h.setPaymentStatus(HousePaymentStatusEnum.COMPLETE_PAY.getValue()));
                        houseRepository.saveAll(houseList);
                    }

                    // 更新"已确认待交租"的合同状态
                    if (!completedContracts.isEmpty()) {
                        List<Contract> contractList = contractRepository.findByStatusAndContractNubmerIn(ContractStatusEnum.WAITING_RENT.getValue(), completedContracts);
                        contractList.forEach(c -> c.setStatus(ContractStatusEnum.WAITING_RECORD.getValue()));
                        contractRepository.saveAll(contractList);

                        Date date = new Date();
                        for (String contractNumber : completedContracts) {
                            //更新租金/押金待办事项状态
                            BacklogItemContractBill contractBill = backlogItemContractBillRepository.findByContractNumber(contractNumber);
                            if (contractBill != null) {
                                Optional<BacklogItem> itemOpt = backlogItemRepository.findById(contractBill.getBacklogItemId());
                                if (itemOpt.isPresent()) {
                                    BacklogItem item = itemOpt.get();
                                    item.setBusinessStatus("已缴费");
                                    item.setHandleStatus(1);
                                    item.setHandlerTime(date);
                                    backlogItemRepository.save(item);
                                }
                            }
                            //生成信息备案待提交待办事项
                            Contract contract = contractRepository.findByContractNubmer(contractNumber);
                            if (contract == null) {
                                LOG.error("WxPayService handleLifePay<微信app生活缴费账单账单支付回调> 未找到合同信息, contractNumber={}", contractNumber);
                                return ResultBean.failedResultWithMsg("未找到合同信息");
                            }
                            BacklogItem submitItem = new BacklogItem();
                            submitItem.setHouseId(contract.getHouseId());
                            submitItem.setType(BacklogItemTypeEnum.RECORD_SUBMIT.getValue());
                            submitItem.setTitle("公租房信息备案待提交");
                            submitItem.setBusinessStatus("待提交");
                            submitItem.setHandleStatus(0);
                            submitItem.setMatchUserId(contract.getMatchUserId());
                            submitItem.setCreateTime(new Date());
                            BacklogItem save = backlogItemRepository.save(submitItem);

                            BacklogItemRecordSubmit submit = new BacklogItemRecordSubmit();
                            submit.setBacklogItemId(save.getId());
                            submit.setMatchUserId(contract.getMatchUserId());
                            backlogItemRecordSubmitRepository.save(submit);
                        }
                    }
                }

                HousePaymentOrder paymentOrder = new HousePaymentOrder();
                paymentOrder.setBillAmount(billAmount);
                paymentOrder.setOrderNumber(redisVo.getOutTradeNo());
                paymentOrder.setPayType(1);
                paymentOrder.setPayMode(redisVo.getPaymentMode());
                paymentOrder.setPayTime(payTime);
                paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
                // 手续费 千分之6
                Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
                paymentOrder.setWxCommissionAmount(payHandlingFee);
                paymentOrder.setPayUserId(redisVo.getUserId());
                paymentOrder.setTotalAmount(0);
                paymentOrder.setPayResult(1);
                housePaymentOrderRepository.save(paymentOrder);
            }

            if (redisVo.getType() == 2) {
                List<EstateRentBill> estateRentBills = new ArrayList<>();
                List<EstateExpenseBill> estateExpenseBills = new ArrayList<>();
                if (!CollectionUtils.isEmpty(redisVo.getIds())) {
                    estateRentBills = estateRentBillRepository.findByIdIn(redisVo.getIds());
                }
                if (!CollectionUtils.isEmpty(redisVo.getExpenseIds())) {
                    estateExpenseBills = estateExpenseBillRepository.findByIdIn(redisVo.getExpenseIds());
                }

                if (CollectionUtils.isEmpty(estateRentBills) && CollectionUtils.isEmpty(estateExpenseBills)) {
                    LOG.error("WxPayService handleLifePay<微信app生活缴费账单账单支付回调> 未找到相关费用信息 outTradeNo={}", redisVo.getOutTradeNo());
                    return ResultBean.failedResultWithMsg("未找到相关费用信息");
                }

                LOG.info("WxPayService handleLifePay, redisVo={}, estateRentBills={}, estateExpenseBills={}", JSON.toJSONString(redisVo), JSON.toJSONString(estateRentBills),
                        JSON.toJSONString(estateExpenseBills));

                List<EstatePaymentOrderRelation> porList = new ArrayList<>();
                for (EstateRentBill b : estateRentBills) {
                    if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                        continue;
                    }
                    // 修改状态为已缴费
                    b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
                    b.setPaymentTime(payTime);
                    b.setPaymentChannel(1);
                    billAmount += b.getCost();

                    EstatePaymentOrderRelation por = new EstatePaymentOrderRelation();
                    por.setOrderNumber(redisVo.getOutTradeNo());
                    por.setBillId(b.getId());
                    por.setPlatformCommissionAmount(redisVo.getPlat());
                    por.setMerchantId(redisVo.getMerchantId());
                    por.setBillAmount(b.getCost());
                    if (b.getChargeType() == 1) {
                        por.setBusinessType(BusinessTypeEnum.RENT_FEE.getValue());
                    } else if (b.getChargeType() == 2) {
                        por.setBusinessType(BusinessTypeEnum.DEPOSIT_FEE.getValue());
                    }
                    porList.add(por);
                }
                estateRentBillRepository.saveAll(estateRentBills);

                for (EstateExpenseBill b : estateExpenseBills) {
                    if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                        continue;
                    }
                    // 修改状态为已缴费
                    b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
                    b.setPaymentTime(payTime);
                    b.setPaymentChannel(1);
                    billAmount += b.getCost();

                    EstatePaymentOrderRelation por = new EstatePaymentOrderRelation();
                    por.setOrderNumber(redisVo.getOutTradeNo());
                    por.setBillId(b.getId());
                    por.setPlatformCommissionAmount(redisVo.getPlat());
                    por.setMerchantId(redisVo.getMerchantId());
                    por.setBillAmount(b.getCost());
                    // 其它费用类型转换
                    if (b.getChargeType() == 1) {
                        por.setBusinessType(BusinessTypeEnum.WATER_FEE.getValue());
                    } else if (b.getChargeType() == 2) {
                        por.setBusinessType(BusinessTypeEnum.ELECTRIC_FEE.getValue());
                    } else if (b.getChargeType() == 3) {
                        por.setBusinessType(BusinessTypeEnum.PROPERTY_FEE.getValue());
                    } else if (b.getChargeType() == 4) {
                        por.setBusinessType(BusinessTypeEnum.BROADBAND_FEE.getValue());
                    } else if (b.getChargeType() == 5) {
                        por.setBusinessType(BusinessTypeEnum.TV_FEE.getValue());
                    } else if (b.getChargeType() == 6) {
                        por.setBusinessType(BusinessTypeEnum.COALGAS_FEE.getValue());
                    } else if (b.getChargeType() == 7) {
                        por.setBusinessType(BusinessTypeEnum.HEATING_FEE.getValue());
                    }
                    porList.add(por);
                }
                estateExpenseBillRepository.saveAll(estateExpenseBills);

                estatePaymentOrderRelationRepository.saveAll(porList);

                EstatePaymentOrder paymentOrder = new EstatePaymentOrder();
                paymentOrder.setBillAmount(billAmount);
                paymentOrder.setOrderNumber(redisVo.getOutTradeNo());
                paymentOrder.setPayType(1);
                paymentOrder.setPayMode(redisVo.getPaymentMode());
                paymentOrder.setPayTime(payTime);
                paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
                // 手续费 千分之6
                Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
                paymentOrder.setWxCommissionAmount(payHandlingFee);
                paymentOrder.setPayUserId(redisVo.getUserId());
                paymentOrder.setTotalAmount(0);
                paymentOrder.setPayResult(1);
                estatePaymentOrderRepository.save(paymentOrder);
            }

            return resultBean;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }*/

    public ResultBean<Map<String, Object>> zeroPayment(PaymentBillRedisVo redisVo) {
        try {
            ResultBean<Map<String, Object>> resultBean = new ResultBean<>();
            resultBean.setCode("10009");
            resultBean.setMsg("0元支付成功");

            Date payTime = new Date();
            Integer billAmount = 0;

            List<RentBill> rentBills = new ArrayList<>();
            List<ExpenseBill> expenseBills = new ArrayList<>();
            List<EstateRentBill> estateRentBills = new ArrayList<>();
            List<EstateExpenseBill> estateExpenseBills = new ArrayList<>();
            if (!CollectionUtils.isEmpty(redisVo.getIds())) {
                rentBills = rentBillRepository.findByIdIn(redisVo.getIds());
            }
            if (!CollectionUtils.isEmpty(redisVo.getExpenseIds())) {
                expenseBills = expenseBillRepository.findByIdIn(redisVo.getExpenseIds());
            }
            if (!CollectionUtils.isEmpty(redisVo.getEstateRentIds())) {
                estateRentBills = estateRentBillRepository.findByIdIn(redisVo.getEstateRentIds());
            }
            if (!CollectionUtils.isEmpty(redisVo.getEstateExpenseIds())) {
                estateExpenseBills = estateExpenseBillRepository.findByIdIn(redisVo.getEstateExpenseIds());
            }

            if (CollectionUtils.isEmpty(rentBills) && CollectionUtils.isEmpty(expenseBills)
                    && CollectionUtils.isEmpty(estateRentBills) && CollectionUtils.isEmpty(estateExpenseBills)) {
                LOG.error("WxPayService handleLifePay<微信app生活缴费账单账单支付回调> 未找到相关费用信息 outTradeNo={}", redisVo.getOutTradeNo());
                return ResultBean.failedResultWithMsg("未找到相关费用信息");
            }

            LOG.info("AliPayService handleAioScanPay<支付宝生活缴费账单支付回调>, redisVo={}", JSON.toJSONString(redisVo));

            List<HousePaymentOrderRelation> porList = new ArrayList<>();
            List<EstatePaymentOrderRelation> porList2 = new ArrayList<>();
            for (RentBill b : rentBills) {
                if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                    continue;
                }
                // 修改状态为已缴费
                b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
                b.setPaymentTime(payTime);
                b.setPaymentChannel(2);
                billAmount += b.getCost();

                HousePaymentOrderRelation por = new HousePaymentOrderRelation();
                por.setOrderNumber(redisVo.getOutTradeNo());
                por.setBillId(b.getId());
                por.setPlatformCommissionAmount(redisVo.getPlat());
                por.setMerchantId(redisVo.getMerchantId());
                por.setBillAmount(b.getCost());
                if (b.getChargeType() == 1) {
                    por.setBusinessType(BusinessTypeEnum.RENT_FEE.getValue());
                } else if (b.getChargeType() == 2) {
                    por.setBusinessType(BusinessTypeEnum.DEPOSIT_FEE.getValue());
                }
                porList.add(por);
            }
            rentBillRepository.saveAll(rentBills);

            for (ExpenseBill b : expenseBills) {
                if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                    continue;
                }
                // 修改状态为已缴费
                b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
                b.setPaymentTime(payTime);
                b.setPaymentChannel(2);
                billAmount += b.getCost();

                HousePaymentOrderRelation por = new HousePaymentOrderRelation();
                por.setOrderNumber(redisVo.getOutTradeNo());
                por.setBillId(b.getId());
                por.setPlatformCommissionAmount(redisVo.getPlat());
                por.setMerchantId(redisVo.getMerchantId());
                por.setBillAmount(b.getCost());
                // 其它费用类型转换
                if (b.getChargeType() == 1) {
                    por.setBusinessType(BusinessTypeEnum.WATER_FEE.getValue());
                } else if (b.getChargeType() == 2) {
                    por.setBusinessType(BusinessTypeEnum.ELECTRIC_FEE.getValue());
                } else if (b.getChargeType() == 3) {
                    por.setBusinessType(BusinessTypeEnum.PROPERTY_FEE.getValue());
                } else if (b.getChargeType() == 4) {
                    por.setBusinessType(BusinessTypeEnum.BROADBAND_FEE.getValue());
                } else if (b.getChargeType() == 5) {
                    por.setBusinessType(BusinessTypeEnum.TV_FEE.getValue());
                } else if (b.getChargeType() == 6) {
                    por.setBusinessType(BusinessTypeEnum.COALGAS_FEE.getValue());
                } else if (b.getChargeType() == 7) {
                    por.setBusinessType(BusinessTypeEnum.HEATING_FEE.getValue());
                } else if (b.getChargeType() == 10) {
                    // 退租
                    por.setBusinessType(BusinessTypeEnum.OTHER_FEE.getValue());
                    // 更新退租账单状态
                    withDrawService.changeStatus(b.getId(), b.getHouseId());
                }
                porList.add(por);
            }
            expenseBillRepository.saveAll(expenseBills);

            for (EstateRentBill b : estateRentBills) {
                if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                    continue;
                }
                // 修改状态为已缴费
                b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
                b.setPaymentTime(payTime);
                b.setPaymentChannel(2);
                billAmount += b.getCost();

                EstatePaymentOrderRelation por = new EstatePaymentOrderRelation();
                por.setOrderNumber(redisVo.getOutTradeNo());
                por.setBillId(b.getId());
                por.setPlatformCommissionAmount(redisVo.getPlat());
                por.setMerchantId(redisVo.getMerchantId());
                por.setBillAmount(b.getCost());
                if (b.getChargeType() == 1) {
                    por.setBusinessType(BusinessTypeEnum.RENT_FEE.getValue());
                } else if (b.getChargeType() == 2) {
                    por.setBusinessType(BusinessTypeEnum.DEPOSIT_FEE.getValue());
                }
                porList2.add(por);
            }
            estateRentBillRepository.saveAll(estateRentBills);

            for (EstateExpenseBill b : estateExpenseBills) {
                if (b.getPaymentStatus() == RrentBillPaymentStatusTypeEnum.PAY.getValue()) {
                    continue;
                }
                // 修改状态为已缴费
                b.setPaymentStatus(RrentBillPaymentStatusTypeEnum.PAY.getValue());
                b.setPaymentTime(payTime);
                b.setPaymentChannel(2);
                billAmount += b.getCost();

                EstatePaymentOrderRelation por = new EstatePaymentOrderRelation();
                por.setOrderNumber(redisVo.getOutTradeNo());
                por.setBillId(b.getId());
                por.setPlatformCommissionAmount(redisVo.getPlat());
                por.setMerchantId(redisVo.getMerchantId());
                por.setBillAmount(b.getCost());
                // 其它费用类型转换
                if (b.getChargeType() == 1) {
                    por.setBusinessType(BusinessTypeEnum.WATER_FEE.getValue());
                } else if (b.getChargeType() == 2) {
                    por.setBusinessType(BusinessTypeEnum.ELECTRIC_FEE.getValue());
                } else if (b.getChargeType() == 3) {
                    por.setBusinessType(BusinessTypeEnum.PROPERTY_FEE.getValue());
                } else if (b.getChargeType() == 4) {
                    por.setBusinessType(BusinessTypeEnum.BROADBAND_FEE.getValue());
                } else if (b.getChargeType() == 5) {
                    por.setBusinessType(BusinessTypeEnum.TV_FEE.getValue());
                } else if (b.getChargeType() == 6) {
                    por.setBusinessType(BusinessTypeEnum.COALGAS_FEE.getValue());
                } else if (b.getChargeType() == 7) {
                    por.setBusinessType(BusinessTypeEnum.HEATING_FEE.getValue());
                } else if (b.getChargeType() == 10) {
                    // 退租
                    por.setBusinessType(BusinessTypeEnum.OTHER_FEE.getValue());
                    // 更新退租账单状态
                    withDrawService.changeStatus(b.getId(), b.getHouseId());
                }
                porList2.add(por);
            }
            estateExpenseBillRepository.saveAll(estateExpenseBills);

            housePaymentOrderRelationRepository.saveAll(porList);
            estatePaymentOrderRelationRepository.saveAll(porList2);

            //验证租金、押金是否都支付完成，全部支付完成，才能修改公租房与合同状态
            if (!CollectionUtils.isEmpty(redisVo.getIds())) {
                // 根据当前支付的账单明细，找到缴费账单对应的所有合同
                List<RentBillRelation> relationList = rentBillRelationRepository.findByRentBillIdIn(redisVo.getIds());
                Map<String, String> houseMap = new HashMap<>();
                List<String> contractNubmers = new ArrayList<>();
                for (RentBillRelation r : relationList) {
                    houseMap.put(r.getContractNubmer(), r.getHouseId());
                    contractNubmers.add(r.getContractNubmer());
                }
                contractNubmers = contractNubmers.stream().distinct().collect(Collectors.toList());
                // 查询拥有未支付的合同信息
                List<RentBillRelation> noPayBillList = rentBillRelationRepository.findNoPayBill(contractNubmers);

                // 保存全部支付完成(租金 + 押金)的合同编号
                List<String> completedContracts = new ArrayList<>();
                // 保存全部支付完成的公租房id
                List<String> houseIds = new ArrayList<>();

                // 验证合同是否支付完成
                Map<String, String> map = noPayBillList.stream().collect(Collectors.toMap(RentBillRelation::getContractNubmer, RentBillRelation::getHouseId));
                for (String contractNumber : contractNubmers) {
                    String houseId = map.get(contractNumber);
                    if (houseId == null) {
                        completedContracts.add(contractNumber);
                        String sHouseId = houseMap.get(contractNumber);
                        if (StringUtils.isNotBlank(sHouseId)) {
                            houseIds.add(sHouseId);
                        }
                    }
                }

                // 更新公租房合同缴费状态
                if (!houseIds.isEmpty()) {
                    List<House> houseList = houseRepository.findByIdIn(houseIds);
                    houseList.forEach(h -> h.setPaymentStatus(HousePaymentStatusEnum.COMPLETE_PAY.getValue()));
                    houseRepository.saveAll(houseList);
                }

                // 更新"已确认待交租"的合同状态
                if (!completedContracts.isEmpty()) {
                    List<Contract> contractList = contractRepository
                            .findByStatusAndContractNubmerIn(ContractStatusEnum.WAITING_RENT.getValue(), completedContracts);
                    contractList.forEach(c -> c.setStatus(ContractStatusEnum.WAITING_RECORD.getValue()));
                    contractRepository.saveAll(contractList);

                    Date date = new Date();
                    for (String contractNumber : completedContracts) {
                        //更新租金/押金待办事项状态
                        List<BacklogItemContractBill> contractBill = backlogItemContractBillRepository.findByContractNumber(contractNumber);
                        if (contractBill != null && contractBill.size()>0 ) {
                            for (BacklogItemContractBill bill : contractBill) {
                                Optional<BacklogItem> itemOpt = backlogItemRepository.findById(bill.getBacklogItemId());
                                if (itemOpt.isPresent()) {
                                    BacklogItem item = itemOpt.get();
                                    item.setBusinessStatus("已缴费");
                                    item.setHandleStatus(1);
                                    item.setHandlerTime(date);
                                    backlogItemRepository.save(item);
                                }
                            }

                        }
                        //生成信息备案待提交待办事项
                        Contract contract = contractRepository.findByContractNubmer(contractNumber);
                        if (contract == null) {
                            LOG.error("WxPayService handleLifePay<微信app生活缴费账单账单支付回调> 未找到合同信息, contractNumber={}", contractNumber);
                            return ResultBean.failedResultWithMsg("未找到合同信息");
                        }

                        AppUser appUsers = null;
                        if (StringUtils.isNotBlank(contract.getMatchUserId())){
                             appUsers = appUserRepository.findByIdOrEnterpriseUserId(contract.getMatchUserId(), contract.getMatchUserId());
                        }
                        BacklogItem submitItem = new BacklogItem();
                        submitItem.setHouseId(contract.getHouseId());
                        submitItem.setType(BacklogItemTypeEnum.RECORD_SUBMIT.getValue());
                        submitItem.setTitle("公租房信息备案待提交");
                        submitItem.setBusinessStatus("待提交");
                        submitItem.setHandleStatus(0);
                        submitItem.setMatchUserId(contract.getMatchUserId());
                        submitItem.setPhone(appUsers != null ? appUsers.getPhone() : null);
                        submitItem.setCreateTime(new Date());
                        BacklogItem save = backlogItemRepository.save(submitItem);

                        BacklogItemRecordSubmit submit = new BacklogItemRecordSubmit();
                        submit.setBacklogItemId(save.getId());
                        submit.setMatchUserId(contract.getMatchUserId());
                        backlogItemRecordSubmitRepository.save(submit);
                    }
                }
            }

            if (!CollectionUtils.isEmpty(rentBills) || !CollectionUtils.isEmpty(expenseBills)) {
                HousePaymentOrder paymentOrder = new HousePaymentOrder();
                paymentOrder.setBillAmount(billAmount);
                paymentOrder.setOrderNumber(redisVo.getOutTradeNo());
                paymentOrder.setPayType(1);
                paymentOrder.setPayMode(redisVo.getPaymentMode());
                paymentOrder.setPayTime(payTime);
                paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
                // 手续费 千分之6
                Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
                paymentOrder.setWxCommissionAmount(payHandlingFee);
                paymentOrder.setPayUserId(redisVo.getUserId());
                paymentOrder.setTotalAmount(billAmount);
                paymentOrder.setPayResult(1);
                housePaymentOrderRepository.save(paymentOrder);
            }

            if (!CollectionUtils.isEmpty(estateRentBills) || !CollectionUtils.isEmpty(estateExpenseBills)) {
                EstatePaymentOrder paymentOrder = new EstatePaymentOrder();
                paymentOrder.setBillAmount(billAmount);
                paymentOrder.setOrderNumber(redisVo.getOutTradeNo());
                paymentOrder.setPayType(1);
                paymentOrder.setPayMode(redisVo.getPaymentMode());
                paymentOrder.setPayTime(payTime);
                paymentOrder.setPlatformCommissionAmount(redisVo.getPlat());
                // 手续费 千分之6
                Integer payHandlingFee = new BigDecimal(billAmount * 0.006).setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
                paymentOrder.setWxCommissionAmount(payHandlingFee);
                paymentOrder.setPayUserId(redisVo.getUserId());
                paymentOrder.setTotalAmount(billAmount);
                paymentOrder.setPayResult(1);
                estatePaymentOrderRepository.save(paymentOrder);
            }

            return resultBean;
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
            return ResultBean.failedResultOfException();
        }
    }

}
